entry
webpack.config.js 配置文件的 entry,指定打包后文件输出 路径。
方式1:
entry: './src/app.js',
方式2:
entry: ['./src/app.js', './src/app2.js']
方式3:
entry: {
# 生成 main.js
main: {
import: ['./src/app2.js', './src/app.js'],
# dependOn 表示:依赖 lodash 库,打包时,不会打包进去
dependOn: 'lodash',
filename: "chain1/[name].js"
},
# 生成 main2.js
main2: {
import: "./src/app3.js",
dependOn: "lodash",
filename: "chain2/[name].js"
},
lodash: 'lodash'
}
模板文件
多模板文件配置:打包后会生成两个 html 文件,并且可以指定引入的js模块。
plugins: [
# 模板配置
new HtmlWebpackPlugin({
# 模板文件标题
title: "多页面应用",
# 模板文件路径
template: "./index.html",
# 生成的 js 模板文件的 html 中具体位置。
inject: "body",
# 打包后指定文件名
filename: "chain1/index1.html",
# 这里 指定了 entry 的 main 值,引入到 index.html 中
chunks: ['main'],
# js 文件插入模板文件中,,插入具体路径。
publicPath: "http://www.bbb.com/"
}),
new HtmlWebpackPlugin({
template: "./index2.html",
inject: "body",
filename: "chain2/index2.html",
chunks: ["main2"],
publicPath: "http://www.aaa.com/"
})
]
tree-shaking
用于精简打包的代码,在 js 文件中,如果引入其它模块但是未使用的代码,将不打包进去。
webpack.config.js 配置 optimization 属性。
# 生产环境
mode: "production",
optimization: {
usedExports: true
},
配置全局变量
在webpack.config.js 配置文件中,加入如下配置:
const wepback = require("webpack")
plugins: [
new webpack.ProvidePlugin({
# 使用 _ 就表示使用lodash 模块
_: "lodash"
})
]
this指向改成 window
安装 第三方包
npm install imports-loader -D
修改webpack.config.js配置文件
module: {
rules: [
{
# 修改 index.js 里面 this 指向 为 window.
test: require.resolve("./src/index.js"),
use: "imports-loader?wrapper=window"
}
]
}