Webpack随记
命令行常用
–module-bind 模块绑定
–watch 自动更新打包
–progress 查看打包过程
–colors 命令行彩色
–display-modules 查看打包模块
–display-reasons 查看打包模块的原因
webpack –config webpack-dev-config.js 指定配置文件
(webpack hello.js –module-bind ‘css=style-loader!css-loader’ –colors –progress –display-modules –display-reasons –watch)
CLI(命令行界面command-line interface)使用webpack
webpack.config.js
module.exports = { //config }
webpack 在node.js中使用
场景:使用node.js写的一些工具,调用webpack
webpack API
1.entry入口 3种方式:
①通过pass a string,指定一个入口文件(想当然所有依赖通过这个入口加载)
②通过pass an array,把两个平行的文件打包在一起
③通过pass an object,应用场景多页面
entry: "./page"//page下的index.js文件 entry: ["./page/a.js", "./page/b.js"] entry: { page1: "./page1", page2: ["./page2/a.js", "./page2/b.js"] }
2.output输出口
//多入口处理 output:{ fileName: '[name].js'//'[hash].js' 或者 '[chunkhash].js' path: _dirname+'/dist', publicPath: 'http://wds.com/' //打包后引用的js文件将会引用上线绝对地址: index.html中<script type='text/javascript' src='http://wds.com/dist/main.js'></script> }
- plugins插件
var htmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { plugins: [ new htmlWebpackPlugin(); ] }
4.context上下文(默认脚本根 目录)
5.module模块配置
webpack常用插件(我们可以到npm插件官网查看插件的API)
插件:html-webpack-plugin(自动在index.html中引用打包后的js文件,并生成到output根目录下)
plugins: [ new htmlWebpackPlugin({ template: 'index.html',//模板 fileName: 'index-[hash].html',//指定生成页面名称 inject: 'head',//嵌入到head标签中 title: 'This is a title!'//传值到模板html中, chunks: ['main', 'a'],//指定引入的js exculdeChunks: ['b'],//排除b.js minify: { removeComments: true, //删除注释 collapseWhitespace: ture,//删除空格 }//压缩 }) ] <!-- index.html 模板--> <html> <head> <title><%= htmlWebpackPlugin.options.title%></title> </head> </html>
插件:postcss-loader中 autoprefixer 处理css前缀问题
loaders
3种使用方式:
- require(‘./loader! ./dir/file.txt’) //loader.js加载文件txt
- CLI: $webpack –module-bind jade –module-bind ‘css=style!css’ //使用jade loader 加载.jade文件,使用 style、css loader处理.css文件
- 配置项:
{ module:{ loaders: [ {test: /\.jade$, loader: 'jade'}, ] } }