jpls93
jpls93

Reputation: 614

Unexpected token using inline dynamic import with webpack for code splitting

I followed the tutorial on how to do code-splitting with Webpack.

But, when building, it doesn't recognize inline imports.

Normal imports e.g. import join from 'lodash.join work, however.

This SO Question: Unexpected token import with Webpack and Babel asked for the same thing but is still unanswered. So, I created a repository that you can replicate to observe the behavior in a more straightforward manner.

Git repository:

git clone https://github.com/jpls93/code-demo && cd code-demo && git checkout unexpected-token-import &&npm install &&npm install && npm run build

Gif demo: enter image description here

Error message: enter image description here

Upvotes: 1

Views: 1076

Answers (2)

andykenward
andykenward

Reputation: 954

You need to add the plugin babel-plugin-syntax-dynamic-import to your babel config.

I've forked your repo and committed the fix. See commit.

But you will run into another error as you are using async and await. enter image description here

As you babel config in your webpack.config.js is using babel-preset-env the default is to compile for the last 2 versions of browsers (which includes IE 10).

So you need to configure your babel config for the browsers you want to support and add the babel-polyfill. I've committed a quick fix that uses babel-polyfill and the default browsers presets in babel-preset-env. I've turned on debug so you can see what babel plugins are being used.

enter image description here

You could also just use babel-plugin-transform-async-to-generator to support async. But I find using babel-preset-env config much nicer so you can use native browser code when possible.

Upvotes: 1

jpls93
jpls93

Reputation: 614

Answer:

// package.json
 "devDependencies": {
+ "babel-plugin-syntax-dynamic-import": "^6.18.0",

// webpack.config.js
 options: {
   presets: ["env"],
+  plugins: ["syntax-dynamic-import"]
 }

Thanks @andykenward. Saw your fork.

Upvotes: 0

Related Questions