webpack的四大核心概念

2023-06-20,,

webpack中文文档:https://doc.webpack-china.org/concepts/

一、Entry(入口)

1、单个入口(简写)语法
// 语法
entry: string|Array<string> // 用法
module.exports = {
entry: './index.js'
} module.exports = {
entry: ['./index.js', 'app.js']
}
2、多个入口(对象语法)
// 语法
entry: {[entryChunkName: string]: string|Array<string>} // 用法
module.exports = {
entry: {
index: ['./index.js', './app.js'],
vendor: './vendor.js'
}
}
3、多页面应用程
webpack 需要 3 个独立分离的依赖图
const config = {
entry: {
pageOne: './src/pageOne/index.js',
pageTwo: './src/pageTwo/index.js',
pageThree: './src/pageThree/index.js'
}
};

一、output(输出)

1、用法

// 语法
filename 用于输出文件的文件名。
目标输出目录 path 的绝对路径。 const config = {
output: {
filename: 'bundle.js',
path: '/home/proj/public/assets'
}
}; module.exports = config;
2、多个入口起点
{
entry: {
app: './src/app.js',
search: './src/search.js'
},
output: {
filename: '[name].js',
path: __dirname + '/dist'
}
} // 写入到硬盘:./dist/app.js, ./dist/search.js
3、使用 CDN 和资源 hash
output: {
path: "/home/proj/cdn/assets/[hash]",
publicPath: "http://cdn.example.com/assets/[hash]/"
}

三、loader(用于对模块的源代码进行转换)

1.webpack 加载 CSS 文件,或者将 TypeScript 转为 JavaScript。为此,首先安装相对应的 loader:
npm install --save-dev css-loader
npm install --save-dev ts-loader module.exports = {
module: {
rules: [
{ test: /\.css$/, use: 'css-loader' },
{ test: /\.ts$/, use: 'ts-loader' }
]
}
};
2、module.rules 允许你在 webpack 配置中指定多个 loader
 module: {
rules: [
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
}

四、plugins(插件)

1、特点
1.参加打包整个过程
2.打包优化和压缩
3.配置编译时的变量
4.极其灵活
2.用法
// 在打包过程中会使用UglifyJsPlugin这个插件来对代码进行一些压缩整理等
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.optimize.UglifyJsPlugin()
]
} 提取相同的代码
CommonsChunkPlugin 混淆,压缩代码的
UglifyjsWebpackPlugin 功能相关
ExtractTextWebpackPlugin
HtmlWebpackPlugin
HotModuleReplacementPlugin
CopyWbpackPlugin

五、思维图

webpack的四大核心概念的相关教程结束。

《webpack的四大核心概念.doc》

下载本文的Word格式文档,以方便收藏与打印。