首先确保安装了happypack
:
npm install --save-dev happypack
然后,在配置文件中引入HappyPack
:
const HappyPack = require('happypack');
最后,使用以下完整的Webpack配置:
const path = require('path');
const HappyPack = require('happypack');
function resolve(dir) {
return path.join(__dirname, '..', dir);
}
module.exports = {
module: {
rules: [
{
test: /\.js$/,
loader: 'happypack/loader?id=happybabel',
include: [resolve('src')],
exclude: /node_modules/
}
]
},
plugins: [
new HappyPack({
id: 'happybabel',
loaders: ['babel-loader?cacheDirectory'],
threads: 4
})
]
};
在这个示例中,使用了happypack/loader?id=happybabel
来替换原来的babel-loader
,并在plugins
中配置了一个HappyPack
实例,指定了id
为happybabel
,loaders
为['babel-loader?cacheDirectory']
,并设置了threads
为4,表示开启4个线程。这样,Webpack在打包过程中就会使用HappyPack来并行执行babel-loader
,从而提高打包效率。