From 5bbcc6910a3be52bb1141bcf3b09eb48eb4044c5 Mon Sep 17 00:00:00 2001 From: Gleb Bahmutov Date: Mon, 6 Apr 2020 20:04:19 -0400 Subject: [PATCH] feat: allow loading webpack config by filename --- README.md | 13 ++++++++++ plugins/load-webpack/index.js | 45 +++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 plugins/load-webpack/index.js diff --git a/README.md b/README.md index 344b6967..c4aed519 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,19 @@ module.exports = on => { **Bonus:** re-using the config means if you create your application using `create-react-app --typescript`, then TypeScript transpile just works out of the box. See [bahmutov/try-cra-app-typescript](https://github.com/bahmutov/try-cra-app-typescript). +## Your webpack config + +If you have your own webpack config, you can use included plugins file to load it. Here is the configuration using the included plugins file and passing the name of the config file via `env` variable in the `cypress.json` file + +```json +{ + "pluginsFile": "node_modules/cypress-react-unit-test/plugins/load-webpack", + "env": { + "webpackFilename": "demo/config/webpack.dev.js" + } +} +``` + ## Examples All components are in [src](src) folder. All tests are in [cypress/integration](cypress/integration) folder. diff --git a/plugins/load-webpack/index.js b/plugins/load-webpack/index.js new file mode 100644 index 00000000..5a91a5e2 --- /dev/null +++ b/plugins/load-webpack/index.js @@ -0,0 +1,45 @@ +// @ts-check +const path = require('path') +const debug = require('debug')('cypress-react-unit-test') +const webpack = require('@cypress/webpack-preprocessor') +const findWebpack = require('find-webpack') + +module.exports = (on, config) => { + require('@cypress/code-coverage/task')(on, config) + + const webpackFilename = config.env && config.env.webpackFilename + if (!webpackFilename) { + throw new Error( + 'Could not find "webpackFilename" option in Cypress env variables %o', + config.env, + ) + } + debug('got webpack config filename %s', webpackFilename) + const resolved = path.resolve(webpackFilename) + debug('resolved webpack at %s', webpackFilename) + const webpackOptions = require(resolved) + + debug('webpack options: %o', webpackOptions) + + const coverageIsDisabled = + config && config.env && config.env.coverage === false + debug('coverage is disabled? %o', { coverageIsDisabled }) + + const opts = { + coverage: !coverageIsDisabled, + } + + findWebpack.cleanForCypress(opts, webpackOptions) + debug('claned webpack options: %o', webpackOptions) + + const options = { + webpackOptions, + watchOptions: {}, + } + + on('file:preprocessor', webpack(options)) + + // IMPORTANT to return the config object + // with the any changed environment variables + return config +}