简体   繁体   English

javascript条件导入在Firefox中不起作用

[英]javascript conditional import doesn't work in Firefox

I'm building a Vue.js application with the webpack template. 我正在使用webpack模板构建Vue.js应用程序。

Since I have some test that works with mocked api I would need to import those api only when I'm testing. 由于我有一些适用于模拟api的测试,因此仅在测试时才需要导入这些api。 In order to do that I have added a conditional import in my main.js file: 为此,我在main.js文件中添加了条件导入:

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. 这样,当我运行测试时,他们使用的是模拟的api,而当我运行应用程序时,则使用的是实际的api。 The problem is that with this configuration I have the following error in Firefox, as soon as the application starts: 问题在于,使用此配置后,应用程序启动后,Firefox中将出现以下错误:

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? 在Chrome中一切正常...我该如何解决?

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: 编辑:我已经在使用wepback + babel,我的webpack配置是从以下vue模板中获取的: https : //github.com/vuejs-templates/webpack然后我还添加了Babel:

.babelrc .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: 然后在我的webpack.base.conf文件中:

{
  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). import()目前仅在JavaScript提案流程的第3阶段(与ES2015中的importexport不同)。 You cannot rely on Stage 3 proposal support in the wild. 您不能随意依赖第3阶段的提案支持。 Apparently, recent Chrome supports it, and recent Firefox does not, yet. 显然,最近的Chrome支持它,而最近的Firefox还不支持。

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. 如果要在提案至少进入第4阶段之前使用它们,通常必须使用像Babel这样的翻译器和/或像Webpack或Browserify这样的打包器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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