简体   繁体   中英

javascript conditional import doesn't work in Firefox

I'm building a Vue.js application with the webpack template.

Since I have some test that works with mocked api I would need to import those api only when I'm testing. In order to do that I have added a conditional import in my main.js file:

if (process.env.NODE_ENV === 'testing') {
    import('apiMocking')
    .then(() => {
       console.log('mocked api imported');
    });
}

This way, when I run the test, they are using my mocked apis, when I run the application I'm using the actual apis. The problem is that with this configuration I have the following error in Firefox, as soon as the application starts:

SyntaxError: ... 'import' and 'export' may only appear at the top level

And then just a blank page. In Chrome everything works fine...how can I solve this?

EDIT: I am already using wepback + babel, my webpack configuration is taken from this vue template: https://github.com/vuejs-templates/webpack then I also added Babel:

.babelrc

{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2"
  ],
  "plugins": ["transform-vue-jsx", "transform-runtime"]
}

Then in my webpack.base.conf file:

{
  test: /\.js$/,
  loader: 'babel-loader',
  include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},

import() is only currently at Stage 3 in the JavaScript proposals process (unlike import and export , which were in ES2015). You cannot rely on Stage 3 proposal support in the wild. Apparently, recent Chrome supports it, and recent Firefox does not, yet.

If you want to use proposals before they reach Stage 4 (at least), you typically have to use a transpiler like Babel and/or a bundler like Webpack or Browserify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM