Import Maps (experimental)
Import maps control the import behavior of TypeScript/JavaScript, in particular, it can specify the import behavior for bare specifiers.
The import map’s file path can be specified via the Import Maps option in Project -> Project Settings -> Scripting in the top menu bar of the editor. After setting, the import maps function will be enabled and the import maps used will be read from the specified file.
If there is a module that is used by all modules in the project, and the developer does not want other modules to refer to it as a relative path, but rather to give it an alias, then using import maps is a good choice.
For example, if the real absolute path of a module is then all modules to refer to it as import {} from 'foo';
:
"foo"
: specifies the name of the module to map."./assets/lib/foo.ts"
: specifies how to map"foo"
. is a relative path, all relative paths in import maps are relative to the location of the import map’s file itself, so./assets/lib/foo.ts
will be resolved to the absolute path<project>/assets/lib/foo.ts
.
Then 'foo'
will be resolved to the module <project>/assets/lib/foo.ts
when referencing the module in any module using:
Import maps also allows mapping all modules in a given directory.
For example, to map all modules in the project assets/lib/bar-1.2.3
directory, the json file for the import maps would look like this:
This is consistent with alias mapping except that "bar/"
specifies the directory to map to.
This way the modules in the project can all refer to the directory as to refer to modules in the directory bar-1.2.3
.
'bar/baz'
will be resolved to the module <project>/assets/lib/bar-1.2.3/baz.ts
.'bar/qux/quux'
will be resolved to the module <project>/assets/lib/bar-1.2.3/qux/quux.ts
.
TypeScript does not support import maps, which can lead to errors when using it. Additional configuration to tell the TypeScript type checker additional module resolution information.
In the two examples above, the field can be configured in the tsconfig.json
file in the project directory. If this field is not present already, add it. Example:
For more information about import maps features, please refer to the Import Maps documentation.
Support
Cocos Creator supports all features in Import Maps Draft Community Group Report, 12 January 2021 standard.