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.

Example repository


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

Most upvoted comments

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:

"target": "es5",
"module": "esnext",

It works. Though when I set

"target": "es6",
"module": "esnext",

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 module compiler option set to commonjs and 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 module to be esnext as @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.

Value is not accepted. Valid values: "commonjs", "amd", "umd", "system", "es6", "es2015".

@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" in tsconfig.json, Reload your code editor (in my case VSCode) and the error is gone