cypress: cypress.config.ts does not work with ESM: "exports is not defined in ES module scope"

Current behavior

I would expect Cypress to work out of the box with TypeScript and ESM:

  • "type": "module" in package.json

  • The following tsconfig.json:

    {
      "compilerOptions": {
        "target": "ESNext",
        "module": "NodeNext",
        "moduleResolution": "NodeNext"
      }
    }
    
  • The following cypress.config.ts:

    import { defineConfig } from 'cypress';
    
    export default defineConfig({});
    

However, with that setup, Cypress currently fails with the following error:

Your configFile is invalid: /Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts

It threw an error when required, check the stack trace below:

ReferenceError: exports is not defined in ES module scope
    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)
    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)

Desired behavior

Cypress should work with this setup.

Test code to reproduce

Clone https://github.com/nwalters512/cypress-esm-typescript-config, then run yarn && yarn cypress. Observe the following error message:

Cypress Version

10.6.0

Node version

16.13.0

Operating System

macOS 12.5

Debug Logs

cypress:cli:cli cli starts with arguments ["/Users/nathan/.nvm/versions/node/v16.13.0/bin/node","/Users/nathan/git/cypress-esm-typescript-config/node_modules/.bin/cypress","run"] +0ms
  cypress:cli NODE_OPTIONS is not set +0ms
  cypress:cli:cli program parsing arguments +1ms
  cypress:cli:cli running Cypress with args [ Command { _events: [Object: null prototype] { 'option:browser': [Function (anonymous)], 'option:ci-build-id': [Function (anonymous)], 'option:component': [Function (anonymous)], 'option:config': [Function (anonymous)], 'option:config-file': [Function (anonymous)], 'option:e2e': [Function (anonymous)], 'option:env': [Function (anonymous)], 'option:group': [Function (anonymous)], 'option:key': [Function (anonymous)], 'option:headed': [Function (anonymous)], 'option:headless': [Function (anonymous)], 'option:no-exit': [Function (anonymous)], 'option:parallel': [Function (anonymous)], 'option:port': [Function (anonymous)], 'option:project': [Function (anonymous)], 'option:quiet': [Function (anonymous)], 'option:record': [Function (anonymous)], 'option:reporter': [Function (anonymous)], 'option:reporter-options': [Function (anonymous)], 'option:spec': [Function (anonymous)], 'option:tag': [Function (anonymous)], 'option:dev': [Function (anonymous)] }, _eventsCount: 22, _maxListeners: undefined, commands: [], options: [ [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option] ], parent: Command { _events: [Object: null prototype], _eventsCount: 1, _maxListeners: undefined, commands: [Array], options: [Array], parent: null, _allowUnknownOption: false, _args: [], rawArgs: [Array], _scriptPath: '/Users/nathan/git/cypress-esm-typescript-config/node_modules/.bin/cypress', _name: 'cypress', _optionValues: {}, _storeOptionsAsProperties: true, _passCommandToAction: true, _actionResults: [], _actionHandler: null, _executableHandler: false, _executableFile: null, _defaultCommandName: null, _exitCallback: null, _aliases: [], _hidden: false, _helpFlags: '-h, --help', _helpDescription: 'display help for command', _helpShortFlag: '-h', _helpLongFlag: '--help', _hasImplicitHelpCommand: undefined, _helpCommandName: 'help', _helpCommandnameAndArgs: 'help [command]', _helpCommandDescription: 'display help for command', _usage: '<command> [options]', args: [Array], [Symbol(kCapture)]: false }, _allowUnknownOption: false, _args: [], rawArgs: null, _scriptPath: null, _name: 'run', _optionValues: {}, _storeOptionsAsProperties: true, _passCommandToAction: true, _actionResults: [], _actionHandler: [Function: listener], _executableHandler: false, _executableFile: null, _defaultCommandName: null, _exitCallback: null, _aliases: [], _hidden: false, _helpFlags: '-h, --help', _helpDescription: 'display help for command', _helpShortFlag: '-h', _helpLongFlag: '--help', _hasImplicitHelpCommand: 0, _helpCommandName: 'help', _helpCommandnameAndArgs: 'help [command]', _helpCommandDescription: 'display help for command', _usage: '[options]', _description: 'Runs Cypress tests from the CLI without the GUI', _argsDescription: undefined, exit: true, args: [], [Symbol(kCapture)]: false } ] +0ms
  cypress:cli:cli variable-length opts parsed { args: [ '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', '/Users/nathan/git/cypress-esm-typescript-config/node_modules/.bin/cypress', 'run' ], opts: Command { _events: [Object: null prototype] { 'option:browser': [Function (anonymous)], 'option:ci-build-id': [Function (anonymous)], 'option:component': [Function (anonymous)], 'option:config': [Function (anonymous)], 'option:config-file': [Function (anonymous)], 'option:e2e': [Function (anonymous)], 'option:env': [Function (anonymous)], 'option:group': [Function (anonymous)], 'option:key': [Function (anonymous)], 'option:headed': [Function (anonymous)], 'option:headless': [Function (anonymous)], 'option:no-exit': [Function (anonymous)], 'option:parallel': [Function (anonymous)], 'option:port': [Function (anonymous)], 'option:project': [Function (anonymous)], 'option:quiet': [Function (anonymous)], 'option:record': [Function (anonymous)], 'option:reporter': [Function (anonymous)], 'option:reporter-options': [Function (anonymous)], 'option:spec': [Function (anonymous)], 'option:tag': [Function (anonymous)], 'option:dev': [Function (anonymous)] }, _eventsCount: 22, _maxListeners: undefined, commands: [], options: [ [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option], [Option] ], parent: Command { _events: [Object: null prototype], _eventsCount: 1, _maxListeners: undefined, commands: [Array], options: [Array], parent: null, _allowUnknownOption: false, _args: [], rawArgs: [Array], _scriptPath: '/Users/nathan/git/cypress-esm-typescript-config/node_modules/.bin/cypress', _name: 'cypress', _optionValues: {}, _storeOptionsAsProperties: true, _passCommandToAction: true, _actionResults: [], _actionHandler: null, _executableHandler: false, _executableFile: null, _defaultCommandName: null, _exitCallback: null, _aliases: [], _hidden: false, _helpFlags: '-h, --help', _helpDescription: 'display help for command', _helpShortFlag: '-h', _helpLongFlag: '--help', _hasImplicitHelpCommand: undefined, _helpCommandName: 'help', _helpCommandnameAndArgs: 'help [command]', _helpCommandDescription: 'display help for command', _usage: '<command> [options]', args: [Array], [Symbol(kCapture)]: false }, _allowUnknownOption: false, _args: [], rawArgs: null, _scriptPath: null, _name: 'run', _optionValues: {}, _storeOptionsAsProperties: true, _passCommandToAction: true, _actionResults: [], _actionHandler: [Function: listener], _executableHandler: false, _executableFile: null, _defaultCommandName: null, _exitCallback: null, _aliases: [], _hidden: false, _helpFlags: '-h, --help', _helpDescription: 'display help for command', _helpShortFlag: '-h', _helpLongFlag: '--help', _hasImplicitHelpCommand: 0, _helpCommandName: 'help', _helpCommandnameAndArgs: 'help [command]', _helpCommandDescription: 'display help for command', _usage: '[options]', _description: 'Runs Cypress tests from the CLI without the GUI', _argsDescription: undefined, exit: true, args: [], [Symbol(kCapture)]: false } } +44ms
  cypress:cli parsed cli options {} +46ms
  cypress:cli verifying Cypress app +0ms
  cypress:cli checking environment variables +0ms
  cypress:cli checking if executable exists /Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress +2ms
  cypress:cli Binary is executable? : true +1ms
  cypress:cli binaryDir is  /Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app +0ms
  cypress:cli Reading binary package.json from: /Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/package.json +0ms
  cypress:cli Found binary version 10.6.0 installed in: /Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app +2ms
  cypress:cli { verified: true } +1ms
  cypress:cli is Verified ? true +1ms
  cypress:cli:run processing run options { key: null, spec: null, reporter: null, reporterOptions: null, project: '/Users/nathan/git/cypress-esm-typescript-config' } +0ms
  cypress:cli:run --key is not set, looking up environment variable CYPRESS_RECORD_KEY +0ms
  cypress:cli:run run to spawn.start args ["--run-project","/Users/nathan/git/cypress-esm-typescript-config"] +0ms
  cypress:cli needs to start own Xvfb? false +0ms
  cypress:cli spawning, should retry on display problem? false +0ms
  cypress:cli spawn args [ '--no-sandbox', '--', '--run-project', '/Users/nathan/git/cypress-esm-typescript-config', '--cwd', '/Users/nathan/git/cypress-esm-typescript-config', '--userNodePath', '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', '--userNodeVersion', '16.13.0' ] { detached: false, stdio: [ 'inherit', 'inherit', 'pipe' ] } +4ms
  cypress:cli spawning Cypress with executable: /Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress +0ms
  cypress:cli piping child STDERR to process STDERR +3ms
  cypress:ts registering ts-node on directory undefined +0ms
  cypress:ts Running without ts-node hook in environment "production" +30ms
  cypress:server:appdata path: /Users/nathan/Library/Application Support/Cypress/cy/production/cache +0ms
  cypress:server:appdata path: /Users/nathan/Library/Application Support/Cypress/cy/production/browsers +25ms
  cypress:server:cypress starting cypress with argv [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress', '--no-sandbox', '--', '--run-project', '/Users/nathan/git/cypress-esm-typescript-config', '--cwd', '/Users/nathan/git/cypress-esm-typescript-config', '--userNodePath', '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', '--userNodeVersion', '16.13.0' ] +0ms
  cypress:server:args argv array: [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress', '--no-sandbox', '--run-project', '/Users/nathan/git/cypress-esm-typescript-config', '--cwd', '/Users/nathan/git/cypress-esm-typescript-config', '--userNodePath', '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', '--userNodeVersion', '16.13.0' ] +0ms
  cypress:server:args parsed argv options { options: { _: [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress' ], sandbox: false, 'run-project': '/Users/nathan/git/cypress-esm-typescript-config', runProject: '/Users/nathan/git/cypress-esm-typescript-config', cwd: '/Users/nathan/git/cypress-esm-typescript-config', userNodePath: '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', userNodeVersion: '16.13.0' } } +1ms
  cypress:server:args argv parsed: { _: [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress' ], sandbox: false, runProject: '/Users/nathan/git/cypress-esm-typescript-config', cwd: '/Users/nathan/git/cypress-esm-typescript-config', userNodePath: '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', userNodeVersion: '16.13.0', invokedFromCli: true } +1ms
  cypress:server:util:proxy found proxy environment variables {} +0ms
  cypress:server:args options { _: [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress' ], sandbox: false, runProject: '/Users/nathan/git/cypress-esm-typescript-config', cwd: '/Users/nathan/git/cypress-esm-typescript-config', userNodePath: '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', userNodeVersion: '16.13.0', invokedFromCli: true, config: {} } +1ms
  cypress:server:args argv options: { _: [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress' ], sandbox: false, runProject: '/Users/nathan/git/cypress-esm-typescript-config', cwd: '/Users/nathan/git/cypress-esm-typescript-config', userNodePath: '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', userNodeVersion: '16.13.0', invokedFromCli: true, config: {}, projectRoot: '/Users/nathan/git/cypress-esm-typescript-config' } +0ms
  cypress:server:cypress from argv [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress', '--no-sandbox', '--run-project', '/Users/nathan/git/cypress-esm-typescript-config', '--cwd', '/Users/nathan/git/cypress-esm-typescript-config', '--userNodePath', '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', '--userNodeVersion', '16.13.0' ] got options { _: [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress' ], sandbox: false, runProject: '/Users/nathan/git/cypress-esm-typescript-config', cwd: '/Users/nathan/git/cypress-esm-typescript-config', userNodePath: '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', userNodeVersion: '16.13.0', invokedFromCli: true, config: {}, projectRoot: '/Users/nathan/git/cypress-esm-typescript-config' } +4ms
  cypress:server:cypress scaling electron app in headless mode +0ms
  cypress:server:appdata path: /Users/nathan/Library/Application Support/Cypress/cy/production +25ms
  cypress:server:cypress starting in mode run with options { _: [ '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/MacOS/Cypress' ], sandbox: false, runProject: '/Users/nathan/git/cypress-esm-typescript-config', cwd: '/Users/nathan/git/cypress-esm-typescript-config', userNodePath: '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node', userNodeVersion: '16.13.0', invokedFromCli: true, config: {}, projectRoot: '/Users/nathan/git/cypress-esm-typescript-config' } +44ms
  cypress:server:cypress running Electron currently +0ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for Query.cloudLatestRunUpdateSpecData +0ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for Query.cloudProjectBySlug +0ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for Query.cloudProjectsBySlugs +0ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for Query.cloudSpecByPath +0ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for Query.cloudViewer +0ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for Query.versions +0ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for CurrentProject.cloudProject +1ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for RemoteFetchableCloudProjectResult.data +2ms
  cypress:graphql:nexusDeferIfNotLoadedPlugin Adding nexusDeferIfNotLoadedPlugin for RemoteFetchableCloudProjectSpecResult.data +0ms
  cypress:server:browsers:utils getBrowsers +0ms
  cypress:launcher:detect detecting if the following browsers are present [ { name: 'chrome', family: 'chromium', channel: 'stable', displayName: 'Chrome', versionRegex: /Google Chrome (\S+)/m, binary: [ 'google-chrome', 'chrome', 'google-chrome-stable' ], minSupportedVersion: 64 }, { name: 'chromium', family: 'chromium', channel: 'stable', displayName: 'Chromium', versionRegex: /Chromium (\S+)/m, binary: [ 'chromium-browser', 'chromium' ], minSupportedVersion: 64 }, { name: 'chrome', family: 'chromium', channel: 'beta', displayName: 'Chrome Beta', versionRegex: /Google Chrome (\S+) beta/m, binary: 'google-chrome-beta', minSupportedVersion: 64 }, { name: 'chrome', family: 'chromium', channel: 'canary', displayName: 'Canary', versionRegex: /Google Chrome Canary (\S+)/m, binary: 'google-chrome-canary', minSupportedVersion: 64 }, { name: 'firefox', family: 'firefox', channel: 'stable', displayName: 'Firefox', versionRegex: /^Mozilla Firefox ([^\sab]+)$/m, binary: 'firefox', minSupportedVersion: 86, validator: [Function: validator] }, { name: 'firefox', family: 'firefox', channel: 'dev', displayName: 'Firefox Developer Edition', versionRegex: /^Mozilla Firefox (\S+b\S*)$/m, binary: [ 'firefox-developer-edition', 'firefox' ], minSupportedVersion: 86 }, { name: 'firefox', family: 'firefox', channel: 'nightly', displayName: 'Firefox Nightly', versionRegex: /^Mozilla Firefox (\S+a\S*)$/m, binary: [ 'firefox-nightly', 'firefox-trunk' ], minSupportedVersion: 86 }, { name: 'edge', family: 'chromium', channel: 'stable', displayName: 'Edge', versionRegex: /Microsoft Edge (\S+)/m, binary: [ 'edge', 'microsoft-edge' ], minSupportedVersion: 79 }, { name: 'edge', family: 'chromium', channel: 'canary', displayName: 'Edge Canary', versionRegex: /Microsoft Edge Canary (\S+)/m, binary: 'edge-canary', minSupportedVersion: 79 }, { name: 'edge', family: 'chromium', channel: 'beta', displayName: 'Edge Beta', versionRegex: /Microsoft Edge Beta (\S+)/m, binary: 'edge-beta', minSupportedVersion: 79 }, { name: 'edge', family: 'chromium', channel: 'dev', displayName: 'Edge Dev', versionRegex: /Microsoft Edge Dev (\S+)/m, binary: [ 'edge-dev', 'microsoft-edge-dev' ], minSupportedVersion: 79 } ] +0ms
  cypress:scaffold-config:detect Detected cypress.config.ts - using TS +0ms
  cypress:server:video using ffmpeg from /Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/node_modules/@ffmpeg-installer/darwin-arm64/ffmpeg +0ms
  cypress:lifecycle:ProjectConfigIpc fork child process { CHILD_PROCESS_FILE_PATH: '/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/require_async_child.js', configProcessArgs: [ '--projectRoot', '/Users/nathan/git/cypress-esm-typescript-config', '--file', '/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts' ], childOptions: { stdio: 'pipe', cwd: '/Users/nathan/git/cypress-esm-typescript-config', execPath: '/Users/nathan/.nvm/versions/node/v16.13.0/bin/node' } } +0ms
  cypress:lifecycle:ProjectConfigIpc trigger the load of the file +3ms
(node:46444) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
  cypress:server:browsers:utils found browsers { browsers: [ { name: 'chrome', family: 'chromium', channel: 'stable', displayName: 'Chrome', version: '104.0.5112.101', path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', minSupportedVersion: 64, majorVersion: '104' }, { name: 'firefox', family: 'firefox', channel: 'stable', displayName: 'Firefox', version: '103.0.1', path: '/Applications/Firefox.app/Contents/MacOS/firefox', minSupportedVersion: 86, majorVersion: '103' } ] } +161ms
  cypress:server:util:process_profiler current & mean memory and CPU usage by process group:
  cypress:server:util:process_profiler ┌─────────┬───────────┬──────────────┬────────────────┬────────────┬────────────────┬──────────┬──────────────┬─────────────┐
  cypress:server:util:process_profiler │ (index) │   group   │ processCount │      pids      │ cpuPercent │ meanCpuPercent │ memRssMb │ meanMemRssMb │ maxMemRssMb │
  cypress:server:util:process_profiler ├─────────┼───────────┼──────────────┼────────────────┼────────────┼────────────────┼──────────┼──────────────┼─────────────┤
  cypress:server:util:process_profiler │    0    │ 'cypress' │      1       │    '46435'     │   102.3    │     102.3      │  13.19   │    13.19     │    13.19    │
  cypress:server:util:process_profiler │    1    │  'other'  │      2       │ '46438, 46439' │     0      │       0        │   0.39   │     0.39     │    0.39     │
  cypress:server:util:process_profiler │    2    │  'TOTAL'  │      3       │      '-'       │   102.3    │     102.3      │  13.58   │    13.58     │    13.58    │
  cypress:server:util:process_profiler └─────────┴───────────┴──────────────┴────────────────┴────────────┴────────────────┴──────────┴──────────────┴─────────────┘ +0ms
  cypress:lifecycle:child:run_require_async_child:46444 configFile: /Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts +0ms
  cypress:lifecycle:child:run_require_async_child:46444 projectRoot: /Users/nathan/git/cypress-esm-typescript-config +1ms
  cypress:lifecycle:child:run_require_async_child:46444 try loading /Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts +6ms
  cypress:lifecycle:child:run_require_async_child:46444 Loading file /Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts +0ms
  cypress:lifecycle:child:run_require_async_child:46444 User is loading an ESM config file +5ms
  cypress:lifecycle:child:run_require_async_child:46444 importing esm file file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts +0ms
  cypress:lifecycle:child:run_require_async_child:46444 error loading file via native Node.js module loader exports is not defined in ES module scope +29ms
  cypress:lifecycle:ProjectConfigIpc error loading config {
  name: 'Error',
  message: 'Your \x1B[33mconfigFile\x1B[39m is invalid: \x1B[94m/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts\x1B[39m\n' +
    '\n' +
    'It threw an error when required, check the stack trace below:',
  stack: 'ReferenceError: exports is not defined in ES module scope\n' +
    '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' +
    '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' +
    '    at async Promise.all (index 0)\n' +
    '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' +
    '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' +
    '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' +
    '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)',
  type: 'CONFIG_FILE_REQUIRE_ERROR',
  details: 'ReferenceError: exports is not defined in ES module scope\n' +
    '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' +
    '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' +
    '    at async Promise.all (index 0)\n' +
    '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' +
    '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' +
    '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' +
    '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)',
  isCypressErr: true,
  messageMarkdown: 'Your `configFile` is invalid: `/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts`\n' +
    '\n' +
    'It threw an error when required, check the stack trace below:',
  originalError: [Object]
} +213ms
  cypress:lifecycle:ProjectConfigManager catch { name: 'Error', message: 'Your \x1B[33mconfigFile\x1B[39m is invalid: \x1B[94m/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts\x1B[39m\n' + '\n' + 'It threw an error when required, check the stack trace below:', stack: 'ReferenceError: exports is not defined in ES module scope\n' + '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' + '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' + '    at async Promise.all (index 0)\n' + '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' + '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' + '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' + '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)', type: 'CONFIG_FILE_REQUIRE_ERROR', details: 'ReferenceError: exports is not defined in ES module scope\n' + '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' + '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' + '    at async Promise.all (index 0)\n' + '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' + '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' + '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' + '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)', isCypressErr: true, messageMarkdown: 'Your `configFile` is invalid: `/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts`\n' + '\n' + 'It threw an error when required, check the stack trace below:', originalError: { name: 'ReferenceError', message: 'exports is not defined in ES module scope', stack: 'ReferenceError: exports is not defined in ES module scope\n' + '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' + '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' + '    at async Promise.all (index 0)\n' + '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' + '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' + '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' + '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)' } } +0ms
  cypress:lifecycle:ProjectConfigManager catch { name: 'Error', message: 'Your \x1B[33mconfigFile\x1B[39m is invalid: \x1B[94m/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts\x1B[39m\n' + '\n' + 'It threw an error when required, check the stack trace below:', stack: 'ReferenceError: exports is not defined in ES module scope\n' + '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' + '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' + '    at async Promise.all (index 0)\n' + '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' + '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' + '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' + '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)', type: 'CONFIG_FILE_REQUIRE_ERROR', details: 'ReferenceError: exports is not defined in ES module scope\n' + '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' + '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' + '    at async Promise.all (index 0)\n' + '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' + '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' + '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' + '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)', isCypressErr: true, messageMarkdown: 'Your `configFile` is invalid: `/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts`\n' + '\n' + 'It threw an error when required, check the stack trace below:', originalError: { name: 'ReferenceError', message: 'exports is not defined in ES module scope', stack: 'ReferenceError: exports is not defined in ES module scope\n' + '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' + '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' + '    at async Promise.all (index 0)\n' + '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' + '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' + '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' + '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)' } } +1ms
  cypress:server:cypress exiting with err {
  name: 'Error',
  message: 'Your \x1B[33mconfigFile\x1B[39m is invalid: \x1B[94m/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts\x1B[39m\n' +
    '\n' +
    'It threw an error when required, check the stack trace below:',
  stack: 'ReferenceError: exports is not defined in ES module scope\n' +
    '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' +
    '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' +
    '    at async Promise.all (index 0)\n' +
    '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' +
    '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' +
    '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' +
    '    at async EventEmitter.<anonymous> (/Users/nathan/Library/CacheYour configFile is invalid: /Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts

It threw an error when required, check the stack trace below:

ReferenceError: exports is not defined in ES module scope
    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)
    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)
s/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)',
  type: 'CONFIG_FILE_REQUIRE_ERROR',
  details: 'ReferenceError: exports is not defined in ES module scope\n' +
    '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' +
    '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' +
    '    at async Promise.all (index 0)\n' +
    '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' +
    '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' +
    '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' +
    '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)',
  isCypressErr: true,
  messageMarkdown: 'Your `configFile` is invalid: `/Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts`\n' +
    '\n' +
    'It threw an error when required, check the stack trace below:',
  originalError: {
    name: 'ReferenceError',
    message: 'exports is not defined in ES module scope',
    stack: 'ReferenceError: exports is not defined in ES module scope\n' +
      '    at file:///Users/nathan/git/cypress-esm-typescript-config/cypress.config.ts:2:23\n' +
      '    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)\n' +
      '    at async Promise.all (index 0)\n' +
      '    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)\n' +
      '    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)\n' +
      '    at async loadFile (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:106:14)\n' +
      '    at async EventEmitter.<anonymous> (/Users/nathan/Library/Caches/Cypress/10.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_require_async_child.js:116:32)'
  }
} +576ms
  cypress:server:cypress calling exit 1 +1ms
  cypress:server:cypress about to exit with code 1 +0ms
  cypress:server:browsers browsers.kill called with no active instance +0ms
  cypress:proxy:http:util:prerequests metrics: { browserPreRequestsReceived: 0, proxyRequestsReceived: 0, immediatelyMatchedRequests: 0, unmatchedRequests: 0, unmatchedPreRequests: 0 } +0ms
  cypress:cli child event fired { event: 'exit', code: 1, signal: null } +1s
  cypress:cli child event fired { event: 'close', code: 1, signal: null } +1ms

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 5
  • Comments: 45 (16 by maintainers)

Commits related to this issue

Most upvoted comments

Can’t share a reproduction, but I am also having the issue of a newly installed cypress not working if "type":"module" is set in package.json

Running Node both 18.14, tried 16.19 and "cypress": "^12.7.0"

I can confirm that

  • removing "type":"module"
  • or converting cypress.config.ts to cypress.config.js

Resolve the issue

If you use a .js extension with type: module" it will use Node.js and the default ESM loader. To clarify, type: module means “I am using ESM (ES modules)” - the one with import and export.

If you are using .ts, it won’t use Node.js and the default ESM loader – Node.js, out of the box, only works with JavaScript, and doesn’t know how to handle other extensions or languages (like TypeScript).

In this case, we use ts-node. ts-node ships with several loaders - the ones we use are here. There’s two - the default which works with CJS (CommonJs modules, eg module.exports and require) and ESM (import / export).

The conditional logic to decide which loader we use is here.

In your case, I suspect the issue is related to your tsconfig.json, possibly https://github.com/cypress-io/cypress/issues/24111#issuecomment-1445726935. What could be happening is we are using the ESM loader, but your tsconfig.json is compiling the code to CommonJS modules under the hood, which is giving the error you are encountering. https://github.com/cypress-io/cypress/issues/24111#issuecomment-1445726935 might help.

Alternatively, you can do a ts-node specific change like this in your tsconfig.json:

{
  // Most ts-node options can be specified here using their programmatic names.
  "ts-node": {
    // It is faster to skip typechecking.
    // Remove if you want ts-node to do typechecking.
    "transpileOnly": true,
    "compilerOptions": {
      // compilerOptions specified here will override those declared below,
      // but *only* in ts-node.  Useful if you want ts-node and tsc to use
      // different options with a single tsconfig.json.
      "module": "ES2015", // <==== added this, so it will compile to ES modules, not CommonJS
    }
  }
}

The reason this stuff is so confusing is many projects have a single tsconfig.json shared by multiple tools (eg, frontend bundler, server code, and Cypress).

I hope this comment clarifies a bit around what’s actually happening, and helps fix your issue. Let me know if you’ve got any other ongoing issues.

image

I get this during the installation of cypress, with the created config file.

I’m using cypress 14.2.1

I found another solution:

The vite app create this file that refer to another configs…

// tsconfig.json

{
    "compilerOptions": { //<-- add this config to the root tsconfig.json
        "module": "ESNext",
    },
    "files": [],
    "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
}

If you also are having troubles with the typing in your test add this

// tsconfig.node.json

{
    "compilerOptions": {
        {...}
    },
    "include": ["vite.config.ts","cypress.config.ts","cypress/**/*.ts"] //<-- add the cypress files
}

I don’t know if this is the best way, but for me worked in launching the cypress app, detecting the types in the test and compile the project fine.

Hope it helps!

Using Vite, on windows 11, I have the same issue with a tsconfig.json that has 2 different references files :

{
  "files": [],
  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.node.json" }
  ],
}

Even if both tsconfig.*.json files are correct (module, ESM…).

cypress_install_error

If i just copy-paste the content of tsconfig.app.json into tsconfig.json everything works as expected…

So it seems that having references path is an issue

Cypress package version: 13.17.0 Cypress binary version: 13.17.0 Electron version: 27.3.10 Bundled Node version: 18.17.1 Installed Node version : 22.12.0

I got this working with yarn cypress open --config-file cypress.config.mts. I just switched the configuration to a .mts file and it ran just fine. This is with "type": "module" in a ViteJS project. Just incase someone else ends up seeing this.

This is still a problem in the latest cypress 13.13.0 ❗ Had to rename .ts config to the .js as joshrogers857 mentioned above.

I am getting this with Cypress 13.12.0, using the default generated file in a scaffolded Vue app (using Vite).

tsconfig.node.js:

{
  "extends": "@tsconfig/node20/tsconfig.json",
  "include": [
    "vite.config.*",
    "vitest.config.*",
    "cypress.config.*",
    "nightwatch.conf.*",
    "playwright.config.*"
  ],
  "compilerOptions": {
    "composite": true,
    "noEmit": true,
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",

    "module": "ESNext",
    "moduleResolution": "Bundler",
    "types": ["node"]
  }
}

cypress.config.ts:

import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
  },
});

My package.json does include type: module.

Changing the file to a .js extension does fix the problem without needing to remove type:module. I would rather keep it as a .ts file though if there’s a fix?

Proposed fixes do not work for me, I don’t want to remove "type": "module" and the ts-node patches results in an empty stacktrace. I guess I’ll go for another e2e library.

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
    },
  },
});

This worked for me, adding the setupNodeEvents. Thanks!

If this can help anyone, I fixed this issue by simply setting "module": "ESNext" in my tsconfig.json

I don’t understand why this ticket is closed, I also have the issue (cypress 14.2.0)

What worked for me was renaming the cypress.config.ts to cypress.config.mjs or .js.

Adding the setupNodeEvents did not work and I dont want to remove the type: module from my Vite application. Hope it helps!

Same issue as @Vondry. For cypress 13.13.0. Renamed to cypress.config.mjs and preserved type: "module" in package.json worked. Renaming to .js didn’t

I can confirm that we have exactly the same issue when setting type:module in package.json. Maybe someone could explain why changing cypress.config.ts to cypress.config.js makes everything work?

"compilerOptions": { //<-- add this config to the root tsconfig.json
        "module": "ESNext",
    },

This is the proper solution, I guess Cypress should add an option to point to the proper tsconfig. ie. cypress run -tsconfig tsconfig.node.json

I’d expect this to work, too. We should fix this. Thanks for the excellent bug report.

This worked for me.

@Zevaxx thx

I’m using cypress 14.2.1

I found another solution:

The vite app create this file that refer to another configs…

// tsconfig.json

{
    "compilerOptions": { //<-- add this config to the root tsconfig.json
        "module": "ESNext",
    },
    "files": [],
    "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
}

If you also are having troubles with the typing in your test add this

// tsconfig.node.json

{
    "compilerOptions": {
        {...}
    },
    "include": ["vite.config.ts","cypress.config.ts","cypress/**/*.ts"] //<-- add the cypress files
}

I don’t know if this is the best way, but for me worked in launching the cypress app, detecting the types in the test and compile the project fine.

Hope it helps!

Hi @MikeMcC399,

I understand the suggestion to test with the Cypress 15.0 pre-release and open a new issue if the problem persists. However, I believe this issue is still relevant and worth reopening.

The “ReferenceError: exports is not defined in ES module scope” problem appears to affect a wide range of Cypress versions (not just 10.6.0), across multiple operating systems and Node.js versions. This suggests a broader compatibility or configuration issue rather than a version-specific bug.

@rkrisztian This is still an issue in Cypress today, likely from version 10 to present (14.5.1). This isn’t a version specific bug, but rather an issue with how Cypress loads and process the end user configuration file, which I go into depth as to why in #31185.

Reopening this issue would help keep the discussion centralized, preserve the valuable context and history already gathered here, and make it easier for others encountering the same problem to find and contribute to the conversation.

Of course, we can also test with the Cypress 15.0 pre-release as suggested and report back. But in the meantime, I think it would be helpful to keep this issue open for continued visibility and collaboration.

Thanks!

If this issue does persist after the release of Cypress 15, which should be coming soon in the following weeks, I will re-open this issue. But I will say we have about 15 issues that are near duplicates or related to this specific issue and trying to find centralization on conversation is already difficult. The history or context won’t go away from closing the issue and users can still comment on closed issues.

As a side note, I will say this should be really easy to reproduce with using vite CLI on v6

Please re-open this issue. It’s not solved. There are many reports of this being the case.

Personally, I used the workaround of using the .mts file extension for the Cypress config as shown in #23552 (comment).

@kleinfreund this issue is/will be fixed in Cypress 15. The issue is that Cypress 15 hasn’t released yet, so there is a gap in user’s receiving the fix vs the fix being implemented. Obviously, if there are problems are the release of Cypress 15, we will re open this issue

Hello @rkrisztian

I do understand that the issue is generally still relevant. The problem though is that the original details in this issue are outdated and would need to be refreshed.

The original reproduction repo https://github.com/nwalters512/cypress-esm-typescript-config no longer shows the original error message “ReferenceError: exports is not defined in ES module scope” when it is run against Cypress 15 beta.

In fact the reproduction repo is an incomplete project, and already after updating to cypress@11.2.0 it fails to run. Instead it outputs the following error message without any reference to an ESM issue:

The testing type selected (e2e) is not configured in your config file.

Re-opening this issue would only be helpful if there was a complete reproduction in it which failed to run on Cypress 14.x using a non-deprecated Node.js version, which would be minimum Node.js 20.x. I couldn’t find one, but perhaps I have overlooked something?

A new issue with enough details to be able to reproduce the problem on Cypress 14 would allow a better up-to-date check, however given the imminent Cypress 15 release, I would suggest waiting a week and seeing what Cypress 15 delivers.

PS I don’t personally have privileges to re-open issues in this repo, so the above is just my best advice. The Cypress.io team (including @AtofStryker who responded here previously) are the ones to decide.

Hi @MikeMcC399,

I understand the suggestion to test with the Cypress 15.0 pre-release and open a new issue if the problem persists. However, I believe this issue is still relevant and worth reopening.

The “ReferenceError: exports is not defined in ES module scope” problem appears to affect a wide range of Cypress versions (not just 10.6.0), across multiple operating systems and Node.js versions. This suggests a broader compatibility or configuration issue rather than a version-specific bug.

Reopening this issue would help keep the discussion centralized, preserve the valuable context and history already gathered here, and make it easier for others encountering the same problem to find and contribute to the conversation.

Of course, we can also test with the Cypress 15.0 pre-release as suggested and report back. But in the meantime, I think it would be helpful to keep this issue open for continued visibility and collaboration.

Thanks!

Please re-open this issue. It’s not solved. There are many reports of this being the case.

Personally, I used the workaround of using the .mts file extension for the Cypress config as shown in https://github.com/cypress-io/cypress/issues/23552#issuecomment-2322012145.

Actually fixed by https://github.com/cypress-io/cypress/pull/23637 - just tested it out. Going to close this one off, it’ll be in the next release.

Adding a quick test: https://github.com/cypress-io/cypress/pull/23695