【问题标题】:"SyntaxError: Cannot use import statement outside a module" with Babel, Jest, and webpack带有 Babel、Jest 和 webpack 的“语法错误:无法在模块外使用 import 语句”
【发布时间】:2020-06-05 20:15:21
【问题描述】:

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

语法错误:无法在模块外使用 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 - 我认为问题出在 module: false 但如果我不包含它,webpack 不会分块我的文件。


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

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

【问题讨论】:

    标签: webpack jestjs babeljs


    【解决方案1】:

    import 语句只允许在 ES 模块中使用。您的测试在使用 commonjs 模块的 Node 中运行。

    尝试将"type": "module" 添加到您的package.json 文件中

    同时检查您正在运行的 Node 版本,您可以在节点文档https://nodejs.org/api/esm.html#esm_ecmascript_modules 中找到更多信息

    【讨论】:

    • 我试过了,不幸的是不起作用.. babelrc 中的 module:false 不排除 type: module from package.json ?
    【解决方案2】:

    来自Babel Options documentation

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

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

    {
      "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"
          ]
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      由于jest@25.4.0,不再需要转译代码以支持测试中的 esm,因为它本身就支持它。你可以找到here,如何实现它,因为它还没有记录。

      【讨论】:

        猜你喜欢
        • 2020-10-08
        • 2022-11-17
        • 2020-10-10
        • 1970-01-01
        • 1970-01-01
        • 2021-01-30
        • 1970-01-01
        相关资源
        最近更新 更多