webpack同之前的gulp相比,gulp属于非模块化打包工具,webpack属于模块化打包工具,两者的优劣这里不做过多分析(可自行百度)。
目的:是为了分享一下使用过程中,用到的插件、loader、遇到的各种问题以及解决办法,最后会附上最终代码。
在这个项目中,用webpack打包css、scss、js、图片文件、jquery、第三方插件、字体图标,编译es6、压缩html、压缩js、压缩css,基本涵盖了常用的东西。
代码结构如下

下面单独说几个难点
1、打包多页面,使用到的插件是html-wepack-plugin,html-loader,也就是你有多少个页面,就有多少个入口,也就写多少个模版文件。当然,页面过多时,可以考虑遍历处理。
//引入路径插件const path = require('path'); //引入导出html插件const HtmlWebpackPlugin = require('html-webpack-plugin'); const config = { //入口 entry:{ home:'./pages/lawSearchHomepage.js', list:'./pages/lawSearchList.js' }, //出口 output:{ filename: '[name].bundle.js', path: path.resolve(__dirname,'build') },
//插件 plugins: [ //html单独导出插件——首页 new HtmlWebpackPlugin({ filename:'lawSearchHomepage.html',//输出后的文件名称 template:'./pages/lawSearchHomepage.html',//模版页面路径 favicon:'./pages/images/favicon.ico',//页签图标 chunks:['home'],//需要引入的js文件名称 inject: true, hash:true,//哈希值 minify: {//压缩 removeComments: true, collapseWhitespace: true } }), //html单独导出插件——列表页 new HtmlWebpackPlugin({ filename:'lawSearchList.html', template:'./pages/lawSearchList.html', favicon:'./pages/images/favicon.ico', chunks:['list'], inject: true, hash:true, minify: { removeComments: true, collapseWhitespace: true } }) ] } module.exports = config;
2、单独打包css,使用到的插件extract-text-webpack-plugin,loader有style-loader、css-loader、sass-loader、node-sass,因为每个页面要引入相对应的css文件,所以,在js入口文件里通过require('./lawSearchHomepage.scss')引如对应的scss文件,打包后css文件会单独打包,并通过link的形式引入html
//引入导出css插件const ExtractTextPlugin = require('extract-text-webpack-plugin'); //loader{//CSS test:/\.css/, use:ExtractTextPlugin.extract({ use:['css-loader'] }

