webpack进阶未完待续

8次阅读

共计 1487 个字符,预计需要花费 4 分钟才能阅读完成。

一、webpack 基础

  1. 基础配置
entry:"path"/["path"]/{key:path}
output:{
    path:"", // 输出路径
    filename:"", //entry 输出文件名,[name] 为 entry.key
    chunkFilename:"", // 除 entry 外的单独输出 js 文件输出名,[name] 为 require.ensure 第三个参数
    publicPath:"/", // 静态文件引用路径,最好为根路径【不然有意想不到的问题,特别在管理静态文件时】,缺省值为相对于 html 的引用路径。}
module:{},
plugins:[
    new HtmlWebpackPlugin({
            filename: "", // 输出 html 文件
            template: "", // 模板 html
            chunks:[chunkName], // 将打包出的 js 文件自动引入到 html 中,输出 js 文件 chunk 名
            minify:true
    }),
    new MiniCssExtractPlugin({filename: "[name]/css/[name].css", //css 文件输出文件名
       chunkFilename: "[id].css"
    }),
    new OptimizeCssAssetsPlugin(), // 压缩 css],
optimization: {
        minimizer: [
            new UglifyJsPlugin({
                uglifyOptions: {
                    sourceMap: true,
                    comments: false
                }
            })
        ],
        splitChunks: { //js 公共模块代码提取
            chunks: 'all', //async、all、initial
            cacheGroups: { // js 公共模块单独提出文件匹配规则,cacheGroups 会覆盖外层的属性值
                // 公共模块抽离
                commons: { // 未有 test,所以匹配所有公共模块
                    minChunks: 2, // 抽离公共代码时,这个代码块最小被引用的次数
                    name:"static/commonJs/commons",
                    minSize: 0, // This is example is too small to create commons chunks
                    priority:1 // 优先级低
                },
                // 第三方包抽离
                vendors:{
                    test:/node_modules/,
                    minChunks:2,
                    name:'static/commonJs/vendors',
                    priority:10 // 优先级高,先抽离公共此块的模块,再抽离下一个级别的模块
                }
            }
        }
    }
  1. 输出文件总结
chunk【entry js,非 entry js,png、svg 等、css 等文件】输出路径:output.path+chunkName
chunk 文件引用路径:output.publicPath+chunkName
js 公共模块提取:optimization.splitChunks【webpack 内置】, 可通过 optimization.splitChunks.cacheGroups 匹配不同规则,单独提取符合规则的 js 文件

css 文件提取:mini-css-extract-plugin 插件【需要安装第三方包】

二、webpack 性能

三、webpack-dev-server 读写文件原理

将文件写入内存,写入内存中文件为 Buffer 格式。。读取通过 memory-fs 暴露方法读取文件。读取内存文件和往内存中写入文件都在 webpack-dev-middleware 插件中暴露出方法,一般读取文件、写入文件方法在 context.fs 对象中,context 对象操作内存文件方法,由另一个文件中 setFs 扩充。

正文完
 0