介绍 Webpack 是一个模块打包器。它将根据模块的依赖关系进行静态分析,而后将这些模块按照指定的规则生成对应的静态资源; 开发便捷,能替代部分 grunt/gulp 的工做,好比打包、压缩混淆、图片转base64等javascript
// 全局安装 npm install webpack -g
// 进入项目,安装到项目依赖中 npm init npm install webpack --save-dev
每一个项目下都必须配置有一个 webpack.config.js ,它的做用如同常规的 gulpfile.js/Gruntfile.js,做为配置项告诉 webpack 如何工做。css
默认状况下,会搜索当前目录的
webpack.config.js
文件,这个文件是一个 node.js 模块,返回一个 json 格式的配置信息对象,或者经过--config
选项来指定配置文件html
例子:java
module.exports = { entry: "./entry.js", output: { path: __dirname + "/dist", filename: "bundle.js" }, module: { loaders: [ { test: /\.css$/, loader: "style!css" } ] } };
Loader 用于预处理文件node
require
指定经过插件能够添加特定功能webpack
- 内嵌插件
- 第三方插件
内嵌插件,无需安装git
用于在编译期间定义常量github
例子:web
new webpack.DefinePlugin({ PRODUCTION: JSON.stringify(true), VERSION: JSON.stringify("5fa3b9"), BROWSER_SUPPORTS_HTML5: true, TWO: "1+1", "typeof window": JSON.stringify("object") })
拷贝资源插件shell
官方这样解释
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