6

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?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
kasia
  • 288
  • 2
  • 6
  • 23

3 Answers3

4

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"
      ]
    }
  }
}
sdgluck
  • 24,894
  • 8
  • 75
  • 90
0

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

deowk
  • 4,280
  • 1
  • 25
  • 34
  • I've tried, unfortunately doesnt work.. module:false in the babelrc isnot excluding the type: module from package.json ? – kasia Feb 21 '20 at 12:20
0

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.

Radovan Kuka
  • 1,962
  • 1
  • 17
  • 19