I'm building my project with Webpack and using Karma for running tests.
I want to configure Karma to set process.env.NODE_ENV
to "test" for Webpack to perform conditional build of the project for testing environment with URLs mapped to localhost, not production domain name.
For that purpose I make use of Webpack's env-replace-loader
, which reads its configuration file environments.json
and sets variables, such as API_URL, depending on the values of process.env.NODE_ENV
. In production build I use Gulp to set process.env.NODE_ENV
and start webpack. It works.
I want to set process.env.NODE_ENV = 'test'
in testing build, initiated by running karma start karma.conf.js
. Currently I just say process.env.NODE_ENV = "test"
in karma.conf.js
.
Is there a better way to do that?
Besides, I tried to use DefinePlugin of webpack in webpack.config.js
to set this variable like this:
const webpackConfig = {
...
plugins: [
new webpack.DefinePlugin({
process.env: {'NODE_ENV': 'test'}
}),
...
],
...
}
and it won't work: webpack env-replace-loader
curses that Module build failed: TypeError: Cannot read property 'URL' of undefined
- I suppose, it can not access the node reports that it doesn't see
In your webpack config try this JSON.stringify('name') instead. Try something like this:
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
APP_ENV: JSON.stringify('browser')
},
})
],
That works with the webpack running a example or something like that. For example, I'm using that to require CSS when running an example but it get ignored when compiling for production.
I got the same problem with Karma config but I fix that adding the plugin into the webpack part of the Karma config file. It's my file for example:
const webpack = require('webpack');
module.exports = function(config) {
config.set({
browsers: ['PhantomJS'],
files: [
'tests.webpack.js',
{
pattern: 'src/**/__tests__/*.js',
included: false,
served: false,
watched: true
}
],
frameworks: ['jasmine'],
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap', 'coverage'],
},
reporters: ['progress', 'notification'],
webpack: {
devtool: 'inline-source-map',
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' }
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('test')
}
})
],
watch: true
},
webpackServer: {
noInfo: true,
}
});
};
I hope that's helpfull for you too!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With