webpack 打包trunk分析

webpack打包确实是很智能,它会分析你当前文件夹下所有文件,然后决定如何打包如何拆分才是最合理。

前提:webpack 默认有一个(或多个)entry入口。

举例子:入口文件:index.js---什么都不依赖

    页面其他组件:a.js--依赖jquery,vue

    这时候当你执行命令 webpack打包时,它会保持index最小化,把jquery打包到a.js的(trunk)中 实现按需加载

 

    情况二:

    入口文件:index.js---什么都不依赖

    页面其他组件:a.js--依赖jquery,vue

    页面其他组件:b.js-依赖jquery,react

 

    此时,打包,它会发现,页面有共同依赖jquery,所以它会把jquery打包到index.js这个trunk中。这样a和b组件在加载时候就不用重复加载jquery

 

 

当然这个公共抽取打包功能依赖与webpack的一个插件--在webpack.config.js中查看

var path = require('path')
var webpack = require('webpack')

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        chunkFilename: '[name].bundle.js',
        filename: 'build.js'
    },
    module: {
        rules: [
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.scss$/,
                loaders: ['style-loader', 'css-loader', 'sass-loader'],
                include: /src/

            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                include: /src/
            },
        ]
    },
    plugins: [new webpack.optimize.CommonsChunkPlugin({
        name: 'main',
        // Move dependencies to our main file
        children: true,
        // Look for common dependencies in all children,
        minChunks: 2,
        // How many times a dependency must come up before being extracted
    }),]

}
View Code

 

posted @ 2017-03-03 07:49  _白马非马  阅读(726)  评论(0编辑  收藏  举报