Home > Back-end >  Cypress Gitlab ci/cd cannot use import statement outside a module
Cypress Gitlab ci/cd cannot use import statement outside a module

Time:05-04

Hey I got my cypress project written in typescript, the project structure looks as follows

/tests
  /e2e
    /cypress
      /fixtures
      /integration
      /plugins
      ...
    package.json
    tsconfig.json

My tsconfig.json file

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["es6", "dom"],
    "types": ["cypress", "node", "reflect-metadata"],
    "module": "commonjs",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "baseUrl": "."
  },
  "include": ["**/*.ts", "cypress/support/index.js", "plugins/index.js"]
}

I don't have "type": "module" property in my package.json file. Whenever I run my code using gitlab pipelines I got the following error

import "dotenv/config";
^^^^^^
SyntaxError: Cannot use import statement outside a module

I know there was a lot of similar questions, but I feel like I checked them all and I didn't find any answer. Does anyone have any ideas what can I change?

CodePudding user response:

The file must be ES module to use import export syntax. And as you mentioned you have type as commonjs in package.json it will treat all .ts files as scripts. To declare file as a module you have two options

  • Use type: module in your package.json, that will by default treat all .ts files as ES modules.
  • If you want only specific file to be treated as modules you can use .mts extension for those files

CodePudding user response:

The Cypress documentation Types for plugins is slightly misleading, shows module.exports = (on, config) => {} but this leads to the compiler complaint.

The cypress-real-world-app has

import * as dotenv from "dotenv";

dotenv.config({ path: ".env.local" });
dotenv.config();

const awsConfig = require(path.join(__dirname, "../../aws-exports-es5.js"));

export default (on, config) => {
  config.env.defaultPassword = process.env.SEED_DEFAULT_USER_PASSWORD;

In general anything with an export is a module, so you if you have nothing to export, add export {} as a quick hack.

  • Related