02.webpack中多文件打包

1.module,chunk,bundle的区别

  • moudle - 各个源码文件,webpack中一切皆是模块
  • chunk - 多模块合并成的,如entry, import(), splitChunk
  • bundle - 最终的输出文件

2.多文件打包配置

2.1 webpack.common.js
javascript 复制代码
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { srcPath, distPath } = require('./paths')

module.exports = {
    entry: {
        index: path.join(srcPath, 'index.js'),
        other: path.join(srcPath, 'other.js')
    },
    module: {
        rules: [
          // ----- 同上文 ----
        ]
    },
    plugins: [
        // 多入口 - 生成 index.html
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'index.html'),
            filename: 'index.html',
            // chunks 表示该页面要引用哪些 chunk (即上面的 index 和 other),默认全部引用
            // chunks: ['index']  // 只引用 index.js
        }),
        // 多入口 - 生成 other.html
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'other.html'),
            filename: 'other.html',
            // chunks: ['other']  // 只引用 other.js
        })
    ]
}
  • 上面的chunks配置,如果不配置chunks,那么打包出来的结果是默认引入全部js
javascript 复制代码
<body>
    <p>webpack demo</p>
    <input type="text"/>
	<script type="text/javascript" src="index.js"></script>
	<script type="text/javascript" src="other.js"></script>
</body>
  • 如果配置了chunks,那么就只引入对应的结果
javascript 复制代码
<body>
    <p>webpack demo</p>
    <input type="text"/>
     <script type="text/javascript" src="index.js"></script>
</body>
2.2 webpack.prod.js
javascript 复制代码
const path = require('path')
const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const webpackCommonConf = require('./webpack.common.js')
const { smart } = require('webpack-merge')
const { srcPath, distPath } = require('./paths')

module.exports = smart(webpackCommonConf, {
    mode: 'production',
    output: {
        // filename: 'bundle.[contentHash:8].js',  // 打包代码时,加上 hash 戳
        filename: '[name].[contentHash:8].js', // name 即多入口时 entry 的 key
        path: distPath,
        // publicPath: 'http://cdn.abc.com'  // 修改所有静态文件 url 的前缀(如 cdn 域名),这里暂时用不到
    },
    module: {
        rules: [
            //代码重复
        ]
    },
    plugins: [
        new CleanWebpackPlugin(), // 会默认清空 output.path 文件夹
        new webpack.DefinePlugin({
            // window.ENV = 'production'
            ENV: JSON.stringify('production')
        })
    ]
})
  • 多入口时,output出口的【name】变量会对应到入口的变量名
相关推荐
神の愛5 分钟前
左连接查询数据 left join
java·服务器·前端
小码哥_常1 小时前
解锁Android嵌入式照片选择器,让你的App体验丝滑起飞
前端
郑寿昌2 小时前
IIoT本体迁移的领域扩展机制
服务器·前端·microsoft
深海鱼在掘金3 小时前
Next.js从入门到实战保姆级教程(第十一章):错误处理与加载状态
前端·typescript·next.js
深海鱼在掘金3 小时前
Next.js从入门到实战保姆级教程(第十二章):认证鉴权与中间件
前端·typescript·next.js
energy_DT3 小时前
2026年十五五油气田智能增产装备数字孪生,CIMPro孪大师赋能“流动增产工厂”三维可视化管控
前端
龙猫里的小梅啊3 小时前
CSS(四)CSS文本属性
前端·css
MXN_小南学前端3 小时前
watch详解:与computed 对比以及 Vue2 / Vue3 区别
前端·javascript·vue.js
饭小猿人4 小时前
Flutter实现底部动画弹窗有两种方式
开发语言·前端·flutter
让学习成为一种生活方式4 小时前
pbtk v 3.5.0安装与使用--生信工具084
前端·chrome