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

后端 未结 5 1387
星月不相逢
星月不相逢 2021-01-11 14:56

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 u

5条回答
  •  既然无缘
    2021-01-11 15:36

    In case people are coming here for the message...

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

    ... in a Cypress TypeScript project. Here is the answer:

    Cypress does support TypeScript out of the box, as long as you have a tsconfig.json file. However, imports don't work unless you preprocess your TypeScript files.

    Here are the steps:

    1. Install webpack: yarn add -D webpack
    2. Install ts-loader: yarn add -D ts-loader
    3. Install @cypress/webpack-preprocessor: yarn add -D @cypress/webpack-preprocessor

    Now, make sure you have these 3 files,tsconfig.json, webpack.config.js and plugins/index.js on your Cypress folder.

    plugins/index.js:

    const wp = require("@cypress/webpack-preprocessor");
    
    module.exports = on => {
        const options = {
            webpackOptions: require("../webpack.config.js")
        };
        on("file:preprocessor", wp(options));
    };
    

    tsconfig.json:

    {
      "compilerOptions": {
        "strict": true,
        "target": "es5",
        "lib": ["es5", "dom"],
        "types": ["cypress"]
      },
      "include": [
        "**/*.ts"
      ]
    }
    

    webpack.config.js:

    module.exports = {
        mode: 'development',
        resolve: {
            extensions: ['.ts', '.js']
        },
        module: {
            rules: [
                {
                    test: /\.ts$/,
                    exclude: [/node_modules/],
                    use: [
                        {
                            loader: 'ts-loader',
                            options: {
                                // skip typechecking for speed
                                transpileOnly: true
                            }
                        }
                    ]
                }
            ]
        }
    }
    

    It should just work now.

提交回复
热议问题