From fdf0184bb607f980e517e617b2c425343c244eee Mon Sep 17 00:00:00 2001 From: Chris Vaszauskas Date: Wed, 15 Feb 2017 03:11:18 -0600 Subject: [PATCH] Apply forceEnv option to Babel transformation (#379) --- src/index.js | 6 +++++- test/loader.test.js | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/index.js b/src/index.js index 57948bf8..e37f2c9b 100644 --- a/src/index.js +++ b/src/index.js @@ -78,6 +78,7 @@ module.exports = function(source, inputSourceMap) { const globalOptions = this.options.babel || {}; const loaderOptions = loaderUtils.parseQuery(this.query); const userOptions = assign({}, globalOptions, loaderOptions); + const env = userOptions.forceEnv || process.env.BABEL_ENV || process.env.NODE_ENV; const defaultOptions = { inputSourceMap: inputSourceMap, sourceRoot: process.cwd(), @@ -88,7 +89,7 @@ module.exports = function(source, inputSourceMap) { babelrc: exists(userOptions.babelrc) ? read(userOptions.babelrc) : resolveRc(path.dirname(filename)), - env: userOptions.forceEnv || process.env.BABEL_ENV || process.env.NODE_ENV, + env: env, }), }; @@ -129,6 +130,9 @@ module.exports = function(source, inputSourceMap) { }); } + const tmpEnv = process.env.BABEL_ENV; + process.env.BABEL_ENV = env; result = transpile(source, options); + process.env.BABEL_ENV = tmpEnv; this.callback(null, result.code, result.map); }; diff --git a/test/loader.test.js b/test/loader.test.js index 75281040..cbbe168c 100644 --- a/test/loader.test.js +++ b/test/loader.test.js @@ -77,3 +77,43 @@ test.cb("should not throw error on syntax error", (t) => { t.end(); }); }); + +test.cb("should use correct env", (t) => { + const config = { + entry: path.join(__dirname, "fixtures/basic.js"), + output: { + path: t.context.directory, + }, + module: { + loaders: [ + { + test: /\.jsx?/, + loader: babelLoader, + query: { + forceEnv: "testenv", + env: { + testenv: { + presets: ["es2015abc"], + }, + otherenv: { + presets: ["es2015xyz"], + } + } + }, + exclude: /node_modules/, + }, + ], + }, + }; + + webpack(config, (err, stats) => { + t.is(err, null); + + t.true(stats.compilation.errors.length === 1); + + t.truthy(stats.compilation.errors[0].message.match(/es2015abc/)); + t.falsy(stats.compilation.errors[0].message.match(/es2015xyz/)); + + t.end(); + }); +});