webpack
静态模块打包器,本身只能处理js,json。通过loader扩展,处理其他类型的文件
webpack核心概念
Entry
an entry point indicates which module webpack should use to begin building out its internal dependency graph
1 | # 默认 ./src/index.js |
Output
The output property tells webpack where to emit the bundles it creates and how to name these files.
单一配置
1 | const path = require('path'); |
多输出配置
1 | # exports为数组,而非output是数组 |
Module
js module
js 功能模块的逻辑划分
webpack module
js 或者 css依赖关系的一种表述
- js
- node import\export
- commonjs require\module.exports
- ADM define\require
- css
- @import
- url or src
Loader
webpack只能处理js,json,其他的文件类型处理,需要loader进行转换,转换为js模块
通过test进行正则匹配文件,use指定loader
1
2
3
4
5
6
7
8
9
10
11
12 const path = require('path');
module.exports = {
output: {
filename: 'my-first-webpack.bundle.js'
},
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' }
]
}
};
Plugins
完成loader不能完成的事情
1
2
3
4
5
6
7
8
9
10
11
12
13 const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
module.exports = {
module: {
rules: [
{ test: /\.txt$/, use: 'raw-loader' }
]
},
plugins: [
new HtmlWebpackPlugin({template: './src/index.html'})
]
};
Mode
指定构建环境,用于构建不同的版本
1 | # 默认产线 |
Browser Compatibility
webpack supports all browsers that are ES5-compliant (IE8 and below are not supported). webpack needs Promise for import() and require.ensure(). If you want to support older browsers, you will need to load a polyfill before using these expressions.
构建
指定配置文件
1 | "scripts": { |
Targets
指定最终代码,运行环境
1 | module.exports = { |
多运行环境
1 | const path = require('path'); |
resolve
指定默认依赖如何查找
externals直接引用,非打包
1 | module.exports = { |
添加配置文件
React ui添加webpack配置配置
webpack配置
webpack-cli添加配置
1 | npm install @webpack-cli/init |
1 | npx webpack-cli init |
用ts编写webpack.config
安装依赖
1 | npm install --save-dev typescript ts-node @types/node @types/webpack |
ts配置webpack
1 | # 使用import ,非require |
ts配置tsconfig.json校验
- method one: compilerOptions
有关tsconfig.json的介绍请参考
1
2
3
4compilerOptions: {
"module": "commonjs",
"target": "es5",
} - method two:
1
npm install --save-dev tsconfig-paths
- 添加配置tsconfig-for-webpack-config.json,覆盖tsconfig.json
1
2
3
4
5
6
7
8# tsconfig-for-webpack-config.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"esModuleInterop": true
}
} - 定义构建脚本
1
2
3
4
5{
"scripts": {
"build": "cross-env TS_NODE_PROJECT=\"tsconfig-for-webpack-config.json\" webpack"
}
}
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏