Uncaught SyntaxError: Unexpected token import

Bug

What is the current behavior?
In case of development environment such code

if (process.env.NODE_ENV === 'testing') {
  import('somemodule');
}

is transformed by webpack 2.5.1 into this

if (false) {
  import('somemodule');
}

which leads to Uncaught SyntaxError: Unexpected token import error in the latest Chrome.

Node.JS 7.10.0, babel 6.24.1 has syntax-dynamic-import plugin

Author: Fantashit

6 thoughts on “Uncaught SyntaxError: Unexpected token import

  1. Hey guys, maybe I’ll be a little help for you.
    @klimashkin Could you maybe share your webpack and babel configs? I just tried to run following code through webpack:

    if (process.env.NODE_ENV === 'production') {
      import('./something.js');
    }

    and it gets transpiled properly. Just make sure(and it’s also a tip for @anlexN), that you have babel-loader included properly in module section in your configuration with syntax-dynamic-import plugin already mentioned above:

     module: {
        rules: [
          {
            test: /\.js(x?)$/,
            exclude: /(node_modules)/,
            use: [
              {
                loader: 'babel-loader',
              },
            ],
          },
      ],
    }

    and my .babelrc config(you can also include this configuration right within webpack.config.js, see https://github.com/babel/babel-loader#options):

    {
      "presets": [
        [
          "env",
          {
            "modules": false,
            "targets": {
              "browsers": [
                "last 2 versions",
              ]
            }
          }
        ]
      ],
      "plugins": [
        "syntax-dynamic-import"
      ]
    }
  2. I had this same problem (also with module.hot that was turned into false at transpile-time, creating an unreachable block).

    I managed to work around it by including something that could not be evaluated to false at transpile-time, forcing webpack to transpile the contents of the if-block:

    var alwaysFalse = false;
    if (module.hot || alwaysFalse) {
      import('./SomeFile').then(() => {}); // Now this gets transpiled correctly
    }

    Maybe this can help someone else while this gets fixed.

  3. This completely breaks the entire concept of webpack.

    This is 100%% broken.

    Because I use if (module.hot) my app does not work in production…so i am going in and manually deleting all that code everywhere each time i want to go to production… stupid as fuck lolz

    Uglify does not work or i would use that… some it fails because some node module has some file that isnt actually included in anything that has some syntax error

  4. Babel should at least transpile dynamic import on unreachable blocks. This should solve that problem without this painful.

Comments are closed.