我一直试图了解"生产模式"在webpack中。从我现在在webpack 2中的内容开始,您可以运行webpack -p
,但这看起来并不像功能丰富。
我从Webpack 1继承的设置是这样的:
var config = {
context: __dirname + '/app',
entry: './index.js',
output: {
path: __dirname + '/app',
filename: 'bundle.js'
},
plugins: [
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new webpack.ProvidePlugin({
moment: "moment"
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.scss$/,
loader: 'style-loader!css-loader!sass-loader',
exclude: /node_modules/
},
{
test: /\.html$/,
loader: 'raw-loader',
exclude: /node_modules/
}
]
}
};
if (process.env.NODE_ENV === 'production') {
config.output.path = __dirname + '/dist';
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
config.plugins.push(new ExtractTextPlugin("styles.css"));
config.module.loaders({
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "style-loader!css-loader!sass-loader"
})
})
}
module.exports = config;
我真正想要的是在生产模式中使用extract-text-plugin
,我尝试了以下内容:
if (process.env.NODE_ENV === 'production') {
config.output.path = __dirname + '/dist';
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
config.plugins.push(new ExtractTextPlugin("styles.css"));
config.module.loaders({
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "style-loader!css-loader!sass-loader"
})
})
}
我收到以下错误:
config.loaders({
^
TypeError: config.loaders is not a function
答案 0 :(得分:2)
config.module.loaders
是一个数组,因此您需要像插件一样进行推送。但是最后你会得到.scss
的两个加载器配置,这显然不是你想要的。相反,您可以定义一个传递给配置的变量,如下所示:
// Default SCSS loader
var scssLoader = 'style-loader!css-loader!sass-loader';
if (process.env.NODE_ENV === 'production') {
// Overwrite it with the extract-text loader
scssLoader = ExtractTextPlugin.extract({
fallback: "style-loader",
use: "style-loader!css-loader!sass-loader"
})
}
然后配置中的.scss
规则将成为:
{
test: /\.scss$/,
loader: scssLoader,
exclude: /node_modules/
},