TypeScript: Error when trying to use dynamic import with module: "es2015"
TypeScript Version: 2.4.0
Code
import('./utils')
.then(({ sum }) => {
console.log(sum(1, 2))
})
.catch(console.error)
tsconfig.json (short version)
{
"compilerOptions": {
"moduleResolution": "node",
"module": "es2015"
}
}
Expected behavior: No errors
Actual behavior:
Dynamic import cannot be used when targeting ECMAScript 2015 modules. with non-obvious reasons why.
I get error Dynamic import cannot be used when targeting ECMAScript 2015 modules.
when I try to use dynamic import inside typescript project with "module": "es2015"
in configuration. The error message makes it clear that I can’t use import() with
es modules but it doesn’t make sense because import() is part of es modules.
However, it compiles correctly but throw annoing error.
I created a repository to reproduce an error.
npm run build-ts: compile ts files into build/ folder.
npm run build-webpack: compile js into dist/. (Then open index.html to see that everything works fine)
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 16
- Comments: 27 (8 by maintainers)
Commits related to this issue
- Fix error about dynamic import Explanation: https://github.com/Microsoft/TypeScript/issues/16675 — committed to Nitive/typescript-dynamic-import-example by Nitive 7 years ago
- Merge pull request #23957 from paulkoerbitz/16675-better-error-message-for-dynamic-import Fix #16675: Better error message for dynamic import with ES2015 modules — committed to microsoft/TypeScript by mhegazy 6 years ago
You’ll want to use
"module": "esnext". Sorry about the confusion there.Hey, Guys. I still have this issue, even if I set it to
"module": "esnext"Anything more I need to do?
I have similar issue which I don’t really understand. When I set in tsconfig:
It works. Though when I set
I have this error. Can I use esnext together with target=es6 ? Typescript 2.7.2
We should just be more helpful here.
I always had
modulecompiler option set tocommonjsand dynamic imports worked just fine.Updated from 2.5.3 to 2.6.1 earlier today, ran NPM build in my React application and instead of getting errors like @Nitive did I got one bundle file instead of the usual multiple chunks. Changed
moduleto beesnextas @DanielRosenwasser suggested and that fixed the issue!Just leaving it here for people who might have a similar issue.
@tomavic I had to edit both, then works for me
“module”: “esnext” is invalid in a jsconfig.json file.
@tomavic depends what you are after. If u wanna make it work for both app and unit tests then go for root. Cheers
I would like to take a look at improving the error message since this keeps coming up if this is OK.
@hnviradiya9 After making the change
"module": "esnext"intsconfig.json, Reload your code editor (in my case VSCode) and the error is gone