Borislav Hadzhiev
Thu Mar 24 2022·2 min read
Photo by Mārtiņš Zemlickis
To solve the error "Dynamic imports are only supported when the '--module'
flag is set to 'es2020', 'esnext' or 'commonjs'", set the module
option to
esnext
in your tsconfig.json
file and restart your IDE and development
server if necessary.
Here is an example of how the error occurs.
const a = 5; if (Number('5') === a) { // ⛔️ Error: Dynamic imports are only supported when // the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', // 'amd', 'system', 'umd', 'node12', or 'nodenext' .ts(1323) import('./another-file').then((myGlobals) => { console.log(myGlobals.num); console.log(myGlobals.default(myGlobals.num, myGlobals.num)); }); }
The first thing you need to do is check if that you have the module
option set
to esnext
in your tsconfig.json
file.
Note that you may also have to set the option in your tsconfig.app.json
file
if using Angular, or whichever config file is used in your build process.
{ "compilerOptions": { "target": "es6", "module": "esnext", // 👈️ set to esnext // ... your other options }, "include": ["src/**/*"], "exclude": ["node_modules"] }
The module option sets the module system for the project.
You could also try setting module
to commonjs
(suitable for Node.js) or
es2020
, it doesn't necessarily have to be set to esnext
.
The difference between having module
set to es6
and es2020
(or esnext
)
is that es2020
adds support for dynamic imports and import.meta
.
VSCode often glitches and needs a reboot even after you have set the module
option to es2020
or esnext
in your tsconfig.json
file.
If you still get the error after restarting your IDE, make sure that the
module
option in NONE of your tsconfig.*.json
files is set to es6
or
lower.
If you use the include or files options, make sure the file you are using dynamic imports in is included in your project and is being tracked by TypeScript.
If your project uses the
exclude option, make sure
your exclude
array does not exclude the file in which you're using dynamic
imports.
exclude
option changes what the include
option finds, effectively filtering out some folders or files from compilation.If TypeScript can't find the file in which you are using dynamic imports, you
will get the error even after setting module
to esnext
.