Skip to content

Commit

Permalink
build(webpack.config.js): more robust build process
Browse files Browse the repository at this point in the history
Fixes a bug where NODE_ENV would be set to "external" when building externals
(and possibly other NODE_ENV-related oddities)
  • Loading branch information
Xunnamius committed Jul 29, 2021
1 parent fd53fef commit e5c6a99
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,30 @@ const { verifyEnvironment } = require('./expect-env');
const nodeExternals = require('webpack-node-externals');
const debug = require('debug')(`${require('./package.json').name}:webpack-config`);

let env = {};
let sanitizedEnv = {};
let { NODE_ENV, ...sanitizedProcessEnv } = { ...process.env, NODE_ENV: 'production' };

try {
require('fs').accessSync('.env');
env = require('dotenv').config().parsed;
debug('new env vars: %O', env);
({ NODE_ENV, ...sanitizedEnv } = require('dotenv').config().parsed);
debug(`NODE_ENV: ${NODE_ENV}`);
debug('sanitized env: %O', sanitizedEnv);
} catch (e) {
debug(`env support disabled; reason: ${e}`);
}

verifyEnvironment();

const envPlugins = [
// ? NODE_ENV is not a "default" (unlike below) but an explicit overwrite
new DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV)
}),
// ? Load our .env results as the defaults (overridden by process.env)
new EnvironmentPlugin({ ...env, ...process.env }),
// ? Create shim process.env for undefined vars (per my tastes!)
new EnvironmentPlugin({ ...sanitizedEnv, ...sanitizedProcessEnv }),
// ? Create shim process.env for undefined vars
// ! The above already replaces all process.env.X occurrences in the code
// ! first, so plugin order is important here
new DefinePlugin({ 'process.env': '{}' })
];

Expand Down Expand Up @@ -55,7 +63,8 @@ const libConfig = {
stats: {
orphanModules: true,
providedExports: true,
usedExports: true
usedExports: true,
errorDetails: true
},

resolve: { extensions: ['.ts', '.wasm', '.mjs', '.cjs', '.js', '.json'] },
Expand Down Expand Up @@ -88,7 +97,8 @@ const externalsConfig = {
stats: {
orphanModules: true,
providedExports: true,
usedExports: true
usedExports: true,
errorDetails: true
},

resolve: { extensions: ['.ts', '.wasm', '.mjs', '.cjs', '.js', '.json'] },
Expand Down Expand Up @@ -123,7 +133,8 @@ const externalsConfig = {
stats: {
orphanModules: true,
providedExports: true,
usedExports: true
usedExports: true,
errorDetails: true
},
resolve: { extensions: ['.ts', '.wasm', '.mjs', '.cjs', '.js', '.json'] },
Expand Down

0 comments on commit e5c6a99

Please sign in to comment.