“SyntaxError: Cannot use import statement outside a module” with Babel, Jest, and webpack

北城以北 提交于 2021-01-27 05:42:16

问题


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

SyntaxError: Cannot use import statement outside a module

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

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


回答1:


From the Babel Options documentation:

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

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



回答2:


import statements are only permitted in ES modules. Your tests are running in Node which uses commonjs modules.

Try adding "type": "module" to your package.json file

Also check the version of Node you are running, you can find more on this in the node docs https://nodejs.org/api/esm.html#esm_ecmascript_modules




回答3:


Since jest@25.4.0, it is not needed to transpile code to support esm in tests anymore as it supports it natively. You can find here, how to achieve that as it is not documented yet.



来源:https://stackoverflow.com/questions/60337983/syntaxerror-cannot-use-import-statement-outside-a-module-with-babel-jest-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!