cypressvite

import module relative to source root directory in Cypress tests


In my app that's build with Vite I can import modules relative to the source root directory with

import { randomId } from '@/utils/string-utils'

This works because in my vite.config.js I've defined this alias

resolve: {
  alias: {
    '@': path.resolve(__dirname, "./src")
  }
}

But Cypress doesn't know anything about this, so if I want to import the module above in a Cypress file, I have to use something like

import { randomId } from '../../../../src/utils/string-utils'

This is tedious and error-prone, because if the Cypress directory structure changed, the import may no longer work. Is it possible to define something similar to the @ alias that will work in Cypress?


Solution

  • In a Vite project you can define aliases that are available to Cypress e2e tests via the cypress-vite plugin, e.g.

    cypress.config.js

    import { defineConfig } from 'cypress'
    import vitePreprocessor from 'cypress-vite'
    import { fileURLToPath } from 'node:url'
    
    export default defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          on(
            'file:preprocessor',
            vitePreprocessor({
              resolve: {
                alias: {
                  // define two aliases
                  '@cy': fileURLToPath(new URL('./cypress', import.meta.url)),
                  '@': fileURLToPath(new URL('../../src', import.meta.url))
                }
              }
            })
          )
        },
        baseUrl: 'http://localhost:8081'
      }
    })