I came across Path Aliases some time ago. Articles mentioning how developers made imports in their React and node projects look nice. I wondered if I could use this feature in my Cypress automation.
Let me give you some context. So typically imports in my project look like this:
import ProductsPage from '../../pages/ProductsPage'; import Navigation from '../../pages/Navigation'; import testData from '../../../../fixtures/product-listing.json'
But with path aliases, the imports look like:
import ProductsPage from '@pages/ProductsPage'; import Navigation from '@pages/Navigation'; import testData from '@fixtures/product-listing.json'
Cleaner, right ?
Follow along to setup path aliases in your cypress project.
Step 1: Webpack preprocessor
Install webpack preprocessor plugin in your project. This will ultimately help to resolve path aliases.
npm install --save-dev @cypress/webpack-preprocessor
Step 2: Webpack Options
Create webpack options which will contain reference of paths to the aliases. You can keep this object in cypress.config.js
or separate file as per your preference.
const wpOptions = { webpackOptions: { resolve: { alias: { '@pages': path.resolve(__dirname, './cypress/e2e/pages'), '@fixtures': path.resolve(__dirname, './cypress/fixtures'), '@': __dirname, }, }, }, watchOptions: {}, };
Step 3: Configure preprocessor plugin
Next, configure cypress to use webpack preprocessor on every file with options specified in previous step
setupNodeEvents(on, config) { on('file:preprocessor', webpackPreprocessor(wpOptions)); }
Step 4: Add paths to jsconfig
This step will enable intellisense for IDE of your choice. Add following settings to jsconfig.json
file in project root.
{ "compilerOptions": { "paths": { "@pages/*": [ "./cypress/e2e/pages/*" ], "@fixtures/*": [ "./cypress/fixtures/*" ], "@/*": [ "./*" ] } } }
That's all !
Now you can create imports like this
import ProductsPage from '@pages/ProductsPage'; import Navigation from '@pages/Navigation'; import testData from '@fixtures/product-listing.json'
Top comments (0)