介绍
Webpack 是一个模块打包器。它将根据模块的依赖关系进行静态分析,然后将这些模块按照指定的规则生成对应的静态资源;
开发便捷,能替代部分 grunt/gulp 的工作,比如打包、压缩混淆、图片转base64等
// 全局安装
npm install webpack -g
// 进入项目,安装到项目依赖中
npm init
npm install webpack --save-dev
每个项目下都必须配置有一个 webpack.config.js ,它的作用如同常规的 gulpfile.js/Gruntfile.js,作为配置项告诉 webpack 如何工作。
默认情况下,会搜索当前目录的
webpack.config.js文件,这个文件是一个 node.js 模块,返回一个 json 格式的配置信息对象,或者通过--config选项来指定配置文件
例子:
module.exports = {
entry: "./entry.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.css$/, loader: "style!css" }
]
}
};
Loader 用于预处理文件
require 指定通过插件可以添加特定功能
- 内嵌插件
- 第三方插件
内嵌插件,无需安装
用于在编译期间定义常量
例子:
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify("5fa3b9"),
BROWSER_SUPPORTS_HTML5: true,
TWO: "1+1",
"typeof window": JSON.stringify("object")
})
拷贝资源插件
官方这样解释
Copy files and directories in webpack,在webpack中拷贝文件和文件夹
npm install --save-dev copy-webpack-plugin
new CopyWebpackPlugin([patterns], options)
在 web pack.config.js 中添加:
var CopyWebpackPlugin = require("copy-webpack-plugin");
module.exports = {
plugins: [
...
new CopyWebpackPlugin([{
from: __dirname + '/src/index.html',
to: __dirname + '/dist'
}]),
...
]
}
删除编译资源
在编译前,删除之前编译结果目录或文件
npm install clean-webpack-plugin --save-dev
在 web pack.config.js 中添加:
var CleanPlugin = require("clean-webpack-plugin");
module.exports = {
...
plugins: [
...
new CleanPlugin(['dist', 'build']),
...
]
...
}
dist 与 build 为需要删除资源
自动生成html插件
生成 HTML5 文件并注入 webpack 绑定的一系列 js & css,生成对应<script>及<link>标签
https://github.com/ampedandwired/html-webpack-plugin
npm install html-webpack-plugin --save-dev
在 web pack.config.js 中添加:
var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
...
plugins: [
...
new HtmlWebpackPlugin({
filename: 'index.html',
template:'./src/template.html',
})
...
]
...
}
filename: 生成文件名称,默认 index.html
template: 模版文件目录及名称
此插件会受到 file-loader 的影响
npm install babel-loader --save-dev
npm install babel-preset-es2015 --save-dev
......
module: {
loaders: [
...
{ test: /\.jsx?$/,loader: 'babel-loader', query: {presets: ['es2015']}}
]
},
resolve:{
extensions:['','.js','.jsx']
},
......
基于 webpack 构建封装
集成了一些常用的 loaders 与 plugins
npm i atool-build -g