Skip to main content
Cypress App

Preprocessors API

A preprocessor is the plugin responsible for preparing a support file or a spec file for the browser.

A preprocessor could transpile your file from another language (ClojureScript) or from a newer version of JavaScript (ES2017).

A preprocessor also typically watches the source files for changes, processes them again, and then notifies Cypress to re-run the tests.

Examples​

We've created some example preprocessors as reference for you to look at. These examples are fully functioning preprocessors.

The code contains comments that explain how it uses the preprocessor API.

Defaults​

When your config doesn't register a file:preprocessor event, Cypress bundles end-to-end spec and support files with @cypress/webpack-batteries-included-preprocessor. Cypress ships its own copy of this preprocessor, so the default needs no install. The batteries-included preprocessor wraps the lower-level @cypress/webpack-preprocessor and adds the loaders and webpack options for:

  • ES2015+ and JSX via Babel
  • TypeScript, when your project has typescript installed, including the aliases under compilerOptions.paths in your tsconfig.json
  • The buffer, os, path, process, and stream Node built-ins
  • Watching and caching files

Change the default webpack config for end-to-end specs​

Most changes to how Cypress bundles end-to-end specs are small: an extra module rule, a resolve.alias, or a resolve.fallback for a Node built-in. You can make that one change on top of the default webpack config instead of rebuilding the config by hand.

If your project already has its own webpack config, pass that config to @cypress/webpack-preprocessor instead, as shown in the webpack preprocessor options.

The batteries-included preprocessor's getFullWebpackOptions() returns a copy of the default webpack config. Change the copy and pass it back to the batteries-included preprocessor, and everything else the default does keeps working.

caution

Start from @cypress/webpack-batteries-included-preprocessor, not from @cypress/webpack-preprocessor's defaultOptions. The lower-level defaults only run JavaScript through Babel, so starting from them drops TypeScript support and the Node built-ins the default config provides.

Install the batteries-included preprocessor packages​

Install @cypress/webpack-batteries-included-preprocessor and version 8 of @cypress/webpack-preprocessor in your project. With npm, first add this overrides entry to your package.json. The entry makes npm use your project's version of @cypress/webpack-preprocessor everywhere, including inside the batteries-included package:

package.json
{
"overrides": {
"@cypress/webpack-preprocessor": "$@cypress/webpack-preprocessor"
}
}

Then install both packages:

npm install @cypress/webpack-batteries-included-preprocessor @cypress/webpack-preprocessor@^8 --save-dev

The batteries-included package lists version 6 of @cypress/webpack-preprocessor as its peer dependency, and version 6 fails TypeScript specs with the following error. Without the override, npm won't install version 8. Yarn, pnpm, and Bun install version 8 and print a peer dependency warning.

TypeError: webpack_preprocessor_1.default.getResolvedTypescriptVersion is not a function

Add a webpack rule to the default end-to-end config​

The following config adds a rule that imports .txt files as strings and keeps everything else from the default config:

const { defineConfig } = require('cypress')
const webpackPreprocessor = require('@cypress/webpack-batteries-included-preprocessor')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
const webpackOptions = webpackPreprocessor.getFullWebpackOptions()

// Import .txt files as strings
webpackOptions.module.rules.push({
test: /\.txt$/,
type: 'asset/source',
})

on(
'file:preprocessor',
webpackPreprocessor({
// Keeps TypeScript support. Leave it out if your project doesn't use TypeScript.
typescript: true,
webpackOptions,
})
)
},
},
})

In a TypeScript project, leaving out typescript: true makes specs fail with "You are attempting to run a TypeScript file, but do not have TypeScript installed", even though TypeScript is installed.

The same steps apply to the other common changes:

Resolving import path aliases​

If your spec or support files import modules through path aliases (for example import { user } from '@/fixtures/user'), the preprocessor that bundles those files must know how to resolve the alias, otherwise the spec fails to compile with a "module not found" error.

In a project with TypeScript installed, the default preprocessor already resolves the aliases under compilerOptions.paths in your tsconfig.json, so those imports work with no preprocessor config.

For other aliases, such as ones in the _moduleAliases field of package.json, or for any alias in a project without TypeScript, install the packages from Install the batteries-included preprocessor packages and add a resolve.alias entry to the default webpack options:

const { defineConfig } = require('cypress')
const path = require('path')
const webpackPreprocessor = require('@cypress/webpack-batteries-included-preprocessor')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
const webpackOptions = webpackPreprocessor.getFullWebpackOptions()

webpackOptions.resolve.alias = {
'@': path.resolve(__dirname, 'src'),
}

on(
'file:preprocessor',
webpackPreprocessor({
// Keeps TypeScript support. Leave it out if your project doesn't use TypeScript.
typescript: true,
webpackOptions,
})
)
},
},
})
info

This page covers aliases in end-to-end spec and support files, which the preprocessor bundles. For component testing, the dev server's Vite or Webpack config resolves aliases instead. See Resolving import path aliases.

Resolve import map specifiers in spec files​

Import maps in your application work in Cypress the same way they work in the browser. When you visit a page with a <script type="importmap">, the page's modules resolve the bare specifiers the import map defines.

Spec and support files don't load through that page. The preprocessor bundles them before they reach the browser, so an import map in your application's HTML doesn't apply to them. A spec that imports a specifier only the import map defines fails to compile with a "Module not found" error.

To import the same modules in a spec, map each specifier again where the preprocessor reads it. For example, this import map resolves @app/format.js in the application to /src/format.js:

index.html
<script type="importmap">
{
"imports": {
"@app/": "/src/"
}
}
</script>

The spec imports the same specifier:

cypress/e2e/format.cy.js
const { formatPrice } = require('@app/format.js')

it('formats prices in dollars', () => {
expect(formatPrice(5)).to.equal('$5.00')
})

In a project with TypeScript installed, add the mapping to compilerOptions.paths in your tsconfig.json. The default preprocessor resolves those paths, and TypeScript finds the module's types, with no preprocessor config:

tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"paths": {
"@app/*": ["./src/*"]
}
}
}

allowJs makes TypeScript read types from a .js module such as src/format.js. A project whose mapped modules are .ts files doesn't need allowJs.

In a project without TypeScript, install the packages from Install the batteries-included preprocessor packages and map @app to the src folder under resolve.alias:

const { defineConfig } = require('cypress')
const path = require('path')
const webpackPreprocessor = require('@cypress/webpack-batteries-included-preprocessor')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
const webpackOptions = webpackPreprocessor.getFullWebpackOptions()

webpackOptions.resolve.alias = {
'@app': path.resolve(__dirname, 'src'),
}

on('file:preprocessor', webpackPreprocessor({ webpackOptions }))
},
},
})

An import map's /src/ is a URL path on your server, while paths and resolve.alias point to folders on disk. Point each mapping at the folder your server serves for that URL path.

Excluding files from being watched​

Certain tools generate files as a side effect of a build (for example, *.d.ts files emitted by css-modules-typescript-loader, or *.hot-update.js HMR files). If Cypress watches those generated files and they are re-emitted on each build, you can end up in an infinite reload loop: Cypress detects a change → rebuilds → the tool generates new files → Cypress detects another change → …

To break this cycle, pass a watchOptions.ignored glob pattern (or array of patterns) to the webpack preprocessor. The preprocessor forwards the value directly to webpack's file watcher, which uses anymatch internally and therefore accepts glob strings, regular expressions, or functions.

const { defineConfig } = require('cypress')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
const webpackPreprocessor = require('@cypress/webpack-preprocessor')

on(
'file:preprocessor',
webpackPreprocessor({
watchOptions: {
// Ignore TypeScript declaration files generated during builds
ignored: '**/*.d.ts',
},
})
)
},
},
})

You can also provide an array to ignore several patterns at once:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
const webpackPreprocessor = require('@cypress/webpack-preprocessor')

on(
'file:preprocessor',
webpackPreprocessor({
watchOptions: {
ignored: ['**/*.d.ts', '**/*.hot-update.js'],
},
})
)
},
},
})

For more details on the available watchOptions values, see webpack's watch configuration docs.

note

The excludeSpecPattern configuration option hides files from the list of specs shown in the Cypress UI — it does not affect which files the preprocessor watches. Use watchOptions.ignored (shown above) when you need to prevent specific files from triggering a test rerun.

Usage​

caution

⚠️ This code is part of the setupNodeEvents function and thus executes in the Node environment. You cannot call Cypress or cy commands in this function, but you do have the direct access to the file system and the rest of the operating system.

To use a preprocessor, you should bind to the file:preprocessor event in your setupNodeEvents function:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('file:preprocessor', (file) => {
// ...
})
},
},
})

The callback function should return one of the following:​

  • A promise* that eventually resolves the path to the built file**.
  • A promise* that eventually rejects with an error that occurred during processing.
note

* The promise should resolve only after the file has completed writing to disk. The promise resolving is a signal that the file is ready to be served to the browser.


note

** The built file is the file that the preprocessor creates, which Cypress eventually serves to the browser.

note

If, for example, the source file is spec.cljs, the preprocessor should:

  1. Compile the ClojureScript into JavaScript spec.js
  2. Write that JavaScript file to disk (example: /Users/foo/tmp/spec.js)
  3. Resolve with the absolute path to that file: /Users/foo/tmp/spec.js
caution

Cypress can, and does, call this callback function multiple times with the same filePath.

Cypress calls the callback function any time the browser requests a file. The call happens on each run of the tests.

Make sure not to start a new watcher each time Cypress calls the function. Instead, cache the watcher and, on subsequent calls, return a promise that resolves when the latest version of the file has been processed.

File object​

The file object passed to the callback function has the following properties:

PropertyDescription
filePathThe full path to the source file.
outputPathThe suggested path for saving the preprocessed file to disk. The path is unique to the source file. A preprocessor can choose to write the file elsewhere, but Cypress automatically provides you this value as a convenient default.
shouldWatchA boolean indicating whether the preprocessor should watch for file changes or not.

File events​

The file object passed to the callback function is an Event Emitter.

Receiving 'close' event​

When the running spec, the project, or the browser is closed while running tests, Cypress emits the close event. The preprocessor should do any necessary cleanup in this function, like closing the watcher when watching.

// example
const watcher = fs.watch(filePath /* ... */)

file.on('close', () => {
watcher.close()
})

Sending 'rerun' event​

If watching for file changes, emit rerun after a file has finished being processed to let Cypress know to rerun the tests.

// example
fs.watch(filePath, () => {
file.emit('rerun')
})

Source maps​

Cypress uses source maps to enhance the error experience. Cypress translates stack traces so that they show your source files instead of the generated file that the browser loads. Source maps also enable displaying code frames. Without inline source maps, you do not see code frames.

By default, Cypress includes an inline source map in your spec file, so you get the most out of the error experience. If you modify the preprocessor, ensure that inline source maps are enabled to get the same experience. Some examples of this include:

If using TypeScript with any custom preprocessor, make sure that the TypeScript compiler is generating source maps. You can turn on source map generation by setting the sourceMap option in your tsconfig.json to true. The inlineSourceMap option is not recommended as it does not provide an accurate code frame. See our recommended tsconfig.json as a reference.

Publishing​

Publish preprocessors to npm with the naming convention cypress-*-preprocessor (e.g. cypress-clojurescript-preprocessor).

Use the following npm keywords:

"keywords": [
"cypress",
"cypress-plugin",
"cypress-preprocessor"
]

Feel free to submit your published plugins to our list of plugins.