1.0.1 • Published 8 years ago

commons-version-webpack-plugin v1.0.1

Weekly downloads
3
License
ISC
Repository
github
Last release
8 years ago

commons-version-webpack-plugin

使用

npm install commons-version-webpack-plugin

var CommonsVersionPlugin = require('commons-version-webpack-plugin');

// ... 省略

config.plugins.push(
    new CommonsVersionPlugin({
        commonsName: 'commons',
        onFileName: function (hash) {
            console.log('onFileName');
            return 'js/[name].' + hash.slice(0, 8) + '.bundle.js';
        }
    })
)

背景

也许你接触过CommonsChunkPlugin,通过它来打公共模块,并做long cache,可能会有这样的代码

// webpack.config.js
var config = {
    entry: {
        'commons': [
            'react', 'react-dom'
        ],
        'index': [
            './example/index'
        ]
    },
    output: {
        path: path.join(__dirname, 'build'),
        filename: '[name].[chunkhash:8].bundle.js',
        chunkFilename: '[id].[chunkhash:8].bundle.js',
        publicPath: '/static/build/'
    },
    plugins: [
        new webpack.NoErrorsPlugin(),
        new CommonsChunkPlugin({
            name: 'commons',
            filename: 'js/[name].[hash:8].bundle.js'
        })
    ]
};

兴高采烈打包出来是 js/commons.7279fdf6.bundle.js。 改下入口文件./example/index.js的代码,如添加console.log('gmfe'),再次打包出来文件是js/commons.fceb5fbe.bundle.js

问题来了,公共文件并没有修改,怎么hash变了呢?

对比两次commons.xxx.js的文件可以发现,区别是index.[hash:8].bundle.js的hash值。 也就是说index.js文件变了,index的hash肯定变,所以commons的hash也变。

npm.io

为啥commons会有index的hash值呢? 细心的同学会发现文件开头有这么一行注释// webpackBootstrap,webpackBootstrap中包含了各个模块的的加载信息。

所以搞了一个插件,只对commons依赖的源代码算hash,这样就可以保证commons的hash不变了。

and

目前只自己团队在用,场景比较局限,功能实现简单,同时webpack内部比较复杂,文档比较缺,有bug在所难免,提issue吧。