javascriptviteplaywright

Using import aliases in Playwright files


I'm migrating a suite of tests from Cypress to Playwright. The project uses JavaScript only (no TypeScript) and is built with Vite. In the Cypress config file I can use the cypress-vite plugin to define aliases like so

import vitePreprocessor from 'cypress-vite'

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('file:preprocessor', vitePreprocessor({
          resolve: {
            alias: {
              // Define 2 import aliases
              '@cy': fileURLToPath(new URL('./cypress', import.meta.url)),
              '@': fileURLToPath(new URL('../../src', import.meta.url))
            }
          }
        })
      )
    }  
  }
})

I can use these @ or @cy aliases when importing modules in the Cypress files, e.g.

import LoginPage from '@cy/pages/login-page'
import { formatDate } from '@/utils/date-utils'

Does Playwright have an equivalent feature? If so, how should the aliases be configured?


Solution

  • There's no need for any additional dependencies. I added this file named jsconfig.json as a sibling of the playwright directory

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@cy/*": ["cypress/*"],
          "@/*": ["../../src/*"]
        }
      }
    }
    

    Then I can use the @ and @cy aliases when importing modules in the Playwright files