webpack 打包优化问题

3 篇文章 0 订阅
2 篇文章 0 订阅

1、引用scss开发模式没问题,打包后样式不生效
   原因:生产模式下没配置scss - loader ,在module 下加入或修改以下loader 配置 

    如果需要打包后单独分离css ,则加以下配置

{
    exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/,/\.scss$/],
    loader: require.resolve('file-loader'),
    options: {
        name: 'static/media/[name].[hash:8].[ext]'
    },
},
{
    test:/\.scss$/,
    //loaders:['style-loader','css-loader','sass-loader'],
    use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
            'css-loader',
            {
                loader: 'postcss-loader', 
                options: {
                    plugins() {
                    return [autoprefixer];
                }
            }
        },
        'sass-loader'
    ]
}),
}

2、提取公共模块到一个通用的chunk 中,该方法也有一定弊端,就是在同一模块较多的时候,打包出来的chunk文件较大,而首屏都会引入该文件,严重影响首屏加载渲染,体验较差。所以出现这种情况的时候,建议直接使用cdn 吧。

new webpack.optimize.CommonsChunkPlugin({
    name: 'vendors',
    minChunks: function (module, count) {
        return (module.resource &&/\.js$/.test(module.resource) &&module.resource.indexOf(path.join(__dirname, '../node_modules')) === 0)
    }
});

3、通过externals 配置提取常用库:把我们的依赖资源声明为一个外部依赖,然后通过script外链脚本引入

在webpack.config 中加入配置

externals: {
		'vue': 'Vue',
		'vue-router':'VueRouter',
		'iview': 'iview',
		'xlsx': 'XLSX',
	},

然后设置output 

output: {
//.....
    libraryTarget: 'umd'
}

4、使用 happypack 加速打包

第一种方式,我用了打包总是不成功,最后会抛出一个错误,具体原因未找到

module: {
	rules: [{
		test: /\.(js|jsx)$/,
		// use: ['babel-loader?cacheDirectory'],
		use: 'happypack/loader?id=jsx',
		exclude: /^node_modules$/
	}]
},

plugins: [
    new HappyPack({
	id: 'jsx',
	cache: true,
	threadPool: HappyThreadPool,
	loaders: ['babel-loader']
    })
]

 

5、使用webpack-uglify-parallel 或者 uglifyjs-webpack-plugin来提升压缩速度,新webpack 默认了第二种,但是配置较为简单

更改webpack中自带的uglifyPlugin配置

const os = require('os');
const UglifyJsParallelPlugin = require('webpack-uglify-parallel');
new UglifyJsParallelPlugin({
	workers: os.cpus().length,
	mangle: true,
	compressor: {
		warnings: false,
		drop_console: true,
		drop_debugger: true
	}
})

 

new UglifyJsPlugin({
    uglifyOptions: {
        ie8: false,
		ecma: 8,
		mangle: true,
		output: { comments: false },
		compress: {
			warnings: false, warnings: false,
			drop_console: true,
			pure_funcs: ['console.log']
		}
	},
	sourceMap: false,
	cache: true,
	parallel: os.cpus().length * 4
}),
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值