Give better error message when trying to import something declared as a global
#46,687 创建于 2021年11月4日
仓库指标
- Star
- (48,455 star)
- PR 合并指标
- (平均合并 6天 17小时) (30 天内合并 9 个 PR)
描述
Suggestion
🔍 Search Terms
import global error message
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
If you write import Foo from "foo" and "foo" resolves to a declaration file that is not a module but declares a global named Foo, we should give a better error message suggesting how to resolve the incorrect import. The current one is
File '{0}' is not a module.
Globals are weird so we can’t always tell what the user was trying to do, but I think we can get it right a good chunk of the time by checking whether this file was already included in the program by some other inclusion reason besides this erroneous import—if so, suggest simply removing the import declaration and referencing Foo as a global. If not, suggest dropping the import clause: import Foo from "foo" → import "foo".
Note I think this only applies when every name specified by the import declaration exactly matches a global declared in the resolved file (and the file is not also a module that just happens to declare some globals via global augmentation).
📃 Motivating Example
@soffes hit this when trying to import from shaka-player and vaguely understood what the error message was saying, but not how to resolve it. It was particularly confusing because the file wasn’t already in his program, so upon writing the bad import, everything seemed to work except TypeScript complained at the import declaration site. This looks like the import is actually working but TypeScript is complaining about it for some inscrutable reason, when in fact, the shaka name is resolving only because the bad import successfully gets the global declaration into the program.