"SyntaxError:无法在模块外部使用import语句"与Babel,Jest和Webpack一起使用 [英] "SyntaxError: Cannot use import statement outside a module" with Babel, Jest, and webpack

查看:347
本文介绍了"SyntaxError:无法在模块外部使用import语句"与Babel,Jest和Webpack一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Babel 7,Webpack 4和Jest的配置有疑问. 在运行测试时,出现以下错误:

I have a problem with configurations of Babel 7, Webpack 4 and Jest. While I'm running tests I'm getting following error:

语法错误:无法在模块外部使用import语句

package.json

 "@babel/core": "^7.7.5",
    "@babel/highlight": "^7.8.3",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/preset-env": "^7.8.4",
    "babel-core": "^7.0.0-bridge.0",
    "babel-loader": "^7.1.5",
    "@babel/plugin-transform-runtime": "^7.7.4",
    "@babel/preset-react": "^7.7.4",
    "@babel/runtime": "^7.8.4",
    "babel-jest": "^24.9.0",
    "jest-watch-typeahead": "^0.4.2",
    "vue-jest": "^3.0.5",
    "jest": "^24.9.0",
    "jest-serializer-vue": "^2.0.2",
    "jest-transform-stub": "^2.0.0",

webpack.config.js

  entry: {
      app: ["./src/index.js"]
  },
  output: {
    path: path.resolve('../', 'static/js/'), 
    filename: "[name].js",
    publicPath: '/static/js/', 
    chunkFilename: '[name].chunk.js' 
  }, 

.babelrc -我认为问题出在模块上:false,但是如果我不包括它,则webpack不会对我的文件进行分块.

.babelrc - I assumed that the problem is with module: false but if I dont include that, webpack doesnt chunk my files.


{
  "presets": [
    ["@babel/preset-env", {"modules": false}, "jest" ]
  ],
  "plugins": [
    "@babel/plugin-syntax-dynamic-import" 
  ],
    "env": {  
      "test": {
        "plugins": ["@babel/plugin-transform-runtime"],
      }
    }
} 

当我删除模块:错误测试正在运行时,是否有机会不将模块:false包含在测试中?

When I removed module: false tests were running, are there any chances to dont include module: false into tests?

推荐答案

来自 Babel选项文档:

注意:env [envKey]选项将在根对象中指定的选项之上合并.

Note: env[envKey] options will be merged on top of the options specified in the root object.

因此您可以在测试期间通过在env.test对象中重新声明插件来应用modules: "auto":

So you can apply modules: "auto" during testing by redeclaring the plugin in the env.test object:

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": false
      },
      "jest"
    ]
  ],
  "plugins": [
    "@babel/plugin-syntax-dynamic-import"
  ],
  "env": {
    "test": {
      "presets": [
        [
          "@babel/preset-env",
          {
            "modules": "auto"
          },
          "jest"
        ]
      ],
      "plugins": [
        "@babel/plugin-transform-runtime"
      ]
    }
  }
}

这篇关于"SyntaxError:无法在模块外部使用import语句"与Babel,Jest和Webpack一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆