Babel-loader: Unexpected token when using import()

Created on 23 Jul 2017  路  20Comments  路  Source: babel/babel-loader

I'm submitting a bug report

Webpack Version:
3.3.0

Babel Core Version:
6.25.0

Babel Loader Version:
7.1.1

Please tell us about your environment:
Linux

Current behavior:
Using import function result in

Module build failed: SyntaxError: Unexpected token, expected {

Expected/desired behavior:
Letting webpack handle this.

I read somewhere modules should be disabled for babel, if that's the case I did not found how. Any insight?

Most helpful comment

I have enabled that plugin in .babelrc but still get the error. Any idea?

All 20 comments

You'll need to enable https://babeljs.io/docs/plugins/syntax-dynamic-import/ The import() syntax is still an experimental proposal, so you need to opt-in to Babel's support for it.

I have enabled that plugin in .babelrc but still get the error. Any idea?

@felixfbecker, I just came across the very same issue and adding this plugin fixed it. Make sure you add the property "plugins": ["syntax-dynamic-import"] like this:

{
  "presets": [
    ["env", {
      "targets": {
        "browsers": ["last 2 versions", "> 2%"]
      }
    }]
  ],
  "plugins": ["syntax-dynamic-import"]
}

@felixfbecker do you use SSR ?

getting

Module build failed: TypeError: The plugin "dynamic-import-webpack" didn't export a Plugin instance

.babelrc

{
    "plugins": ["dynamic-import-webpack"],
    "optional": ["es7.decorators", "es7.classProperties", "es7.objectRestSpread"]
}

dependencies:

"babel-core": "^6.26.0",  
"babel-loader": "^7.1.2",  
"babel-plugin-syntax-dynamic-import": "^6.18.0",  
"webpack": "^3.10.0",  

@kjda
you have the plugin specified as "dynamic-import-webpack", its "syntax-dynamic-import"

// try this util i made to avoid issues related to dynamic imports with ssr rendering

export const importAsync = path => typeof System === "object" && typeof System.import === "function" ? System.import(`../${path}`) : null;

how to use?

import {importAsync} from "../../lib/import-async";
const Admin = () => importAsync('components/routes/admin');
console.log(<Admin />);

@felixfbecker Turns out you need babel-plugin-dynamic-import-node
It fixed the issue for me - run it in before you run tests.
However, It will cause Webpack to create a single bundle, so make sure you only use that plugin for tests, and not for your build.

Thanks @rommguy, it solved it for me!

It got solved for me when I changed the webpack's file name from webpack.config.js to webpack.config.babel.js

I am having this issue, none of the above solutions function / are ideal.

Does webpack dynamic importing work with babel?

@komali2 yep, it should. we'll need a bit more info to debug though... can you create a new issue with your configs (or even better, a small repo that repros the issue)?

Ok, thank you, I'll create a new issue

@existentialism I'm not convinced I'm looking at an actual bug, so I'll stay in "support mode" for now. Here's the stack overflow question if you wanna take a crack at it: https://stackoverflow.com/questions/49788115/syntax-error-on-dynamic-import-using-webpack-and-babel

ERROR in ./src/router/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (6:22)

> 6 | const hello2 = () =>  import('../components/admin/hello.vue' );



  "devDependencies": {
    "@vue/server-test-utils": "^1.0.0-beta.25",
    "@vue/test-utils": "^1.0.0-beta.25",
    "babel": "^6.23.0",
    "babel-core": "^6.26.3",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-2": "^6.24.1",


 {
                test: /\.js$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "babel-loader",
                        options: {
                            "presets": [["es2015", {"modules": false}], "react"],
                        },
                    },
                ],
            },

I got the same issue like @BonBonSlick , still, looking for another solution for this

I had the same problem. I tried @babel/plugin-syntax-dynamic-import and babel-plugin-dynamic-import-node but didn't work. So after a couple of hours, I found out that the problem was my 2 configuration files (.babelrc and webpack.config.js). Those configuration files were merging and the result wasn't the expected.

Solution:
Handle your webpack and babel configuration in a single file. I did it on my webpack.config.js file as follows:

module.exports = {
    ...
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: [
                            "@babel/preset-env",
                            "@babel/preset-react"
                        ],
                        plugins: [
                            "@babel/plugin-syntax-dynamic-import"
                        ]
                    }
                }
    ...
};

The solution spotted by @jdgarcia1381 works for me, but I'd prefer to keep the .babelrc file.

Edit: I just found out why it was failing to me. it was a trailing comma I had added in the .babelrc file.
Once this is being imported in my webpack settings and parsed as a json:
options: { ...JSON.parse(fs.readFileSync(path.resolve(__dirname, '../.babelrc'))), },
and my settings were defined as:
"env": { "test": { "plugins" : ["dynamic-import-node"], } }

All I had to do was to search for a json error there, and it was the trailing coma, so I removed it:
"env": { "test": { "plugins" : ["dynamic-import-node"] } }

And now it works like a charm!

issue still exists

webpack.dev.config

import { DEV_ENV } from './global_const';
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');

error

/var/www/test/build/webpack.config.dev.js:11
import { DEV_ENV } from './global_const';
       ^

SyntaxError: Unexpected token {
    at new Script (vm.js:83:7)

any babels plugins do not help

  "plugins": [
    "transform-runtime",
    "syntax-dynamic-import" // OR     "@babel/plugin-syntax-dynamic-import"
  ],
Was this page helpful?
0 / 5 - 0 ratings

Related issues

suzuki-shunsuke picture suzuki-shunsuke  路  23Comments

eoinmurray picture eoinmurray  路  20Comments

jesprider picture jesprider  路  34Comments

dashed picture dashed  路  24Comments

acnovais picture acnovais  路  72Comments