Cypress ParseError: 'import' and 'export' may appear only with 'sourceType: module'

munkacsimark picture munkacsimark · Dec 6, 2018 · Viewed 10.2k times · Source

I updated Cypress from 3.0.3 to 3.1.3. Im using ES6 import/export modules which must be working related to docs. But Im getting a line with undefined in terminal and following error in the GUI:

<root_dir>/node_modules/@babel/runtime/helpers/esm/defineProperty.js:1
export default function _defineProperty(obj, key, value) {
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

My tests are in vanilla JS, no TS os CoffeeScript. Im stuck, in 3.0.3 it worked fine.

Answer

emery picture emery · Jun 20, 2019

This error is caused by the presence of modern keywords like "import" and "export" when Cypress runs in the browser. Unlike Selenium or Protractor -- it actually runs inside the browser. Since browsers don't support modern JS yet, you'll need to use webpack or browserify to transpile your code.

https://docs.cypress.io/api/plugins/preprocessors-api.html#Examples

Here is a fantastic blog post on how to get Cypress to work with modern JS and Typescript using webpack: https://glebbahmutov.com/blog/use-typescript-with-cypress/

^^ The post is focused on TypeScript, but the configuration options for Javascript will be similar.

The following npm packages must be installed and in your package.json:

"@cypress/webpack-preprocessor": "^4.1.0",
"cypress": "^3.3.1",
"ts-loader": "^6.0.3",
"typescript": "^3.5.2",
"webpack": "^4.34.0"

Webpack should be installed using:

npm install --save-dev webpack typescript ts-loader
npm install --save-dev @cypress/webpack-preprocessor

The following should be present under the "compilerOptions" section of a file called tsconfig.json in your root directory, with "allowJs" set to true for non-typescript users:

"module": "es6",
"target": "es6",
"types": ["cypress"],
"allowJs": true

A file called "webpack.config.js" should be present in your root directory with the following:

const path = require('path')

module.exports = {
  entry: './src/index.ts',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
}

And these exports should be present under cypress/plugins/index.js:

const webpack = require('@cypress/webpack-preprocessor')
module.exports = on => {
  const options = {
    // send in the options from your webpack.config.js, so it works the same
    // as your app's code
    webpackOptions: require('../../webpack.config'),
    watchOptions: {}
  }

  on('file:preprocessor', webpack(options))
}

Note this final bit at the end of the Cypress plugins file,

on('file:preprocessor', webpack(options))

That is where Cypress is told to process your modern JS code in such a way as to make it Cypress-runnable.