Last updated: Feb 29, 2024
Reading time·2 min

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) console.log(myGlobals.num); console.log(myGlobals.default) }); }
module to esnext in your tsconfig.json fileThe first thing you need to do is check if 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.
If you get an error, try setting module to commonjs and restart your
development server.
The difference between having module set to es6 and es2020 (or esnext)
is that es2020 adds support for dynamic imports and import.meta.
Restart your IDE and development server after making the changes.
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.
The 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.
If the error persists, check out the following GitHub repository where I've shown a working, minimal example of using dynamic imports.
I've also written a detailed article on how to import values from another file in TS.