这是我的webpack.config.js
var webpack = require("webpack");
module.exports = {
entry: "./entry.js",
devtool: "source-map",
output: {
path: "./dist",
filename: "bundle.min.js"
},
plugins: [
new webpack.optimize.UglifyJsPlugin({minimize: true})
]
};
我用
$ webpack
在dist文件夹里,我只得到
bundle.min.js
bundle.min.js.map
我还想看看未压缩的bundle.js
你可以使用一个配置文件,并使用一个环境变量有条件地包含UglifyJS插件:
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const PROD = JSON.parse(process.env.PROD_ENV || '0');
module.exports = {
entry: './entry.js',
devtool: 'source-map',
output: {
path: './dist',
filename: PROD ? 'bundle.min.js' : 'bundle.js'
},
optimization: {
minimize: PROD,
minimizer: [
new TerserPlugin({ parallel: true })
]
};
然后当你想缩小它时,设置这个变量:
$ PROD_ENV=1 webpack
编辑:
正如评论中提到的,通常使用NODE_ENV(按照约定)来说明特定环境是生产环境还是开发环境。要检查它,你也可以设置const PROD = (process.env。NODE_ENV === 'production'),然后正常继续。
你应该像这样导出一个数组:
const path = require('path');
const webpack = require('webpack');
const libName = 'YourLibraryName';
function getConfig(env) {
const config = {
mode: env,
output: {
path: path.resolve('dist'),
library: libName,
libraryTarget: 'umd',
filename: env === 'production' ? `${libName}.min.js` : `${libName}.js`
},
target: 'web',
.... your shared options ...
};
return config;
}
module.exports = [
getConfig('development'),
getConfig('production'),
];
我也有同样的问题,必须满足以下所有要求:
缩小版+非缩小版(如问题所示)
ES6
跨平台(Windows + Linux)。
我最终解决如下:
webpack.config.js:
const path = require('path');
const MinifyPlugin = require("babel-minify-webpack-plugin");
module.exports = getConfiguration;
function getConfiguration(env) {
var outFile;
var plugins = [];
if (env === 'prod') {
outFile = 'mylib.dev';
plugins.push(new MinifyPlugin());
} else {
if (env !== 'dev') {
console.log('Unknown env ' + env + '. Defaults to dev');
}
outFile = 'mylib.dev.debug';
}
var entry = {};
entry[outFile] = './src/mylib-entry.js';
return {
entry: entry,
plugins: plugins,
output: {
filename: '[name].js',
path: __dirname
}
};
}
package.json:
{
"name": "mylib.js",
...
"scripts": {
"build": "npm-run-all webpack-prod webpack-dev",
"webpack-prod": "npx webpack --env=prod",
"webpack-dev": "npx webpack --env=dev"
},
"devDependencies": {
...
"babel-minify-webpack-plugin": "^0.2.0",
"npm-run-all": "^4.1.2",
"webpack": "^3.10.0"
}
}
然后我可以通过(不要忘记npm install之前):
npm run-script build