您的位置:首页 > Web前端 > Webpack

Webpack配置开发环境 个人土话总结

2017-08-24 14:24 477 查看
本问主要讲解的是webpack.config.js文件的配置,不会讲解webpack是什么,默认你已经安装webpack以及其他npm包,并对webpack有一些了解下面将从webpack.config.js最基本的概念开始src下page文件夹下每个组件子孙文件夹下,基本上都是js和css两个文件 下面正式说明配置文件的配置方法1.js的加载方式,采用官方推荐的方式,也就是不使用loader,默认加载 2.有的时候我们的入口文件entry不止一个js,此时配置一个对象即可,格式如下
entry: {'common':['./src/page/common/index.js'],'index':['./src/page/index/index.js'],'list':['./src/page/list/index.js'],'detail':['./src/page/detail/index.js'],'cart':['./src/page/cart/index.js'],'order-confirm':['./src/page/order-confirm/index.js'],'order-list':['./src/page/order-list/index.js'],'order-detail':['./src/page/order-detail/index.js'],'payment':['./src/page/payment/index.js'],'user-login':['./src/page/user-login/index.js'],'user-register':['./src/page/user-register/index.js'],'user-pass-reset':['./src/page/user-pass-reset/index.js'],'user-pass-update':['./src/page/user-pass-update/index.js'],'user-center':['./src/page/user-center/index.js'],'user-center-update':['./src/page/user-center-update/index.js'],'result':['./src/page/result/index.js'],'about':['./src/page/about/index.js']}
3.输出文件根据不同类型放置在不同文件夹,output配置如下
output: {path: '/dist/',filename: 'js/[name].js'},
现在,name会根据entry里每一个对象属性的key值,生成相应的同名js文件,位置是dist下的js文件夹 4.项目中如果要引入jQuery,可以在每个模块下显示引入 var $ = require('jQuery'),记得首先npm install jQuery --save。这样比较麻烦,所以可以在公共的footer.html里面全局src引入一个cdn上的jQuery,然后为了实现模块化开发,如下在webpack.config.js文件里配置
externals:{'jquery':'window.jQuery'},
现在就可以在每个模块中方向的使用jQuery了5.有些时候我们需要把项目中一下模块提取出来作为公共模块,供其他模块引入,这时候我们需要安装CommonsChunkPlugins,在配置文件里如下设置
var webpack = require('webpack');
以上内容中,name指代entry中需要作为公共模块的那个模块,filename指代将要把它打包到output中path指代的目录下的js文件夹下的base.js里 6.我们用css-loader和style-loader加载样式,但是我们希望css文件打包后单独一个文件夹,而不是默认的那样打包进js文件里,于是我们需要安装extract-text-webpack-plugin,之后配置文件内容如下
plugins:[// 独立通用模块到js/base.jsnew webpack.optimize.CommonsChunkPlugin({name:'common',filename: 'js/base.js'}),// 把css单独打包到文件里new ExtractTextPlugin("css/[name].css"),]
这句话意思就是把css文件单独打包到以output指定的path下的css文件下,生成同名的css文件,接下来,要在loader选项里设置如下
module: {loaders: [{test: /\.css$/,loader:  ExtractTextPlugin.extract("style-loader","css-loader")}]},
这样就保证css正确加载且打包入单独文件夹下 7.webpack处理html模板,为什么还要处理html呢,因为如果我们在开发目录自己写好html,手动引入资源,第一很麻烦,第二指定页面版本号不现实,第三上线一般是dist目录,这样我们引入资源的路径很可能出问题,所以我们应该让webpack帮我们处理html模板,主要用到 html-webpack-plugin / html-loader ,首先安装并引入
var HtmlWebpackPlugin = require('html-webpack-plugin');
首先,我们先把一些公共部分提取出来,这里template就是入口html,filename就是打包的html(路径),favicon指定图标的位置,title就是页面title,inject为true会自动加载页面资源,hash为true会为html加一个哈希值作为版本号,chunks指定哪些资源模块会被html加载,传入两个参数,name为html文件名,title为html页面title,接下来继续配置plugin
plugins:[// 独立通用模块到js/base.jsnew webpack.optimize.CommonsChunkPlugin({name:'common',filename: 'js/base.js'}),// 把css单独打包到文件里new ExtractTextPlugin("css/[name].css"),// html模板的处理new HtmlWebpackPlugin(getHtmlConfig('index','首页')),new HtmlWebpackPlugin(getHtmlConfig('list','商品列表')),new HtmlWebpackPlugin(getHtmlConfig('detail','商品详情')),new HtmlWebpackPlugin(getHtmlConfig('cart','购物车')),new HtmlWebpackPlugin(getHtmlConfig('order-confirm','订单确认')),new HtmlWebpackPlugin(getHtmlConfig('order-list','订单列表')),new HtmlWebpackPlugin(getHtmlConfig('order-detail','订单详情')),new HtmlWebpackPlugin(getHtmlConfig('payment','订单支付')),new HtmlWebpackPlugin(getHtmlConfig('user-login','用户登录')),new HtmlWebpackPlugin(getHtmlConfig('user-register','用户注册')),new HtmlWebpackPlugin(getHtmlConfig('user-pass-reset','找回密码')),new HtmlWebpackPlugin(getHtmlConfig('user-pass-update','找回密码')),new HtmlWebpackPlugin(getHtmlConfig('user-center','个人中心')),new HtmlWebpackPlugin(getHtmlConfig('user-center-update','修改个人信息')),new HtmlWebpackPlugin(getHtmlConfig('result','操作结果')),new HtmlWebpackPlugin(getHtmlConfig('about','关于MMall'))]
如上所示,传入对应的name和title,对html进行了打包处理 8.这里说说webpack对icon-font和图片的处理,这里相对比较简单,用的loader是url-loader,首先安装并引入
var ExtractTextPlugin = require("extract-text-webpack-plugin");
配置如下
module: {loaders: [{test: /\.css$/,loader:  ExtractTextPlugin.extract("style-loader","css-loader")},{test: /\.(gif|png|jpg|woff|svg|eot|ttf)\??.*$/,loader:  'url-loader?limit=100&name=resource/[name].[ext]'}]}
注意的一点是,url-loader会默认把图片转换为base64格式,为了能在文件夹中看到图片文件,可以指定一个limit值,在不小于这个值时,不会把图片转换为base64格式,后面name=resource/[name].[ext] 这句话意思是,在output中path指定的路径下的resource文件夹下生产同名图片,格式不变

9.使用webpack-dev-server实现页面热更新

所谓热更新就是文件保存时,直接刷新页面,而不需要手动刷新,这里用到了webpack-dev-server,它的作用就是实现一个前端开发过程中的服务器,可以实现热更新。其默认的加载方式是iframe,就是我们的页面会成为他生成页面的一个iframe,这有两个缺点,第一会在头部有个默认的黑色框,第二在我们改变文件路径时,url无变化,不利于控制。所以我们采用第二种方式使用它,即在配置文件里entry的公共模块入口指定client,但是因为我们只需要在生产环境使用这个client,所以我们可以配置一个环境变量,使得这个client只在开发环境添加,如下所示
// 环境变量的配置,dev/onlinevar WEBPACK_ENV=process.env.WEBPACK_ENV||'dev';
接着在配置文件中加入如下内容
// 只有开发环境加这句话if('dev'=== WEBPACK_ENV){config.entry.common.push('webpack-dev-server/client?http://localhost:8088/');}
这里我们指定了端口号,已经指定了只有开发环境才会使用它 下面整合配置文件如下
var webpack = require('webpack');var ExtractTextPlugin = require("extract-text-webpack-plugin");var HtmlWebpackPlugin = require('html-webpack-plugin');// 环境变量的配置,dev/onlinevar WEBPACK_ENV=process.env.WEBPACK_ENV||'dev';console.log(WEBPACK_ENV);// 获取html-webpack-plugin参数的方法var getHtmlConfig = function(name,title){return {template:'./src/view/'+name+'.html',filename:'view/'+name+'.html',favicon:'./favicon.ico',title:title,inject:true,hash:true,chunks:['common',''+name+'']}}var config = {entry: {'common':['./src/page/common/index.js'],'index':['./src/page/index/index.js'],'list':['./src/page/list/index.js'],'detail':['./src/page/detail/index.js'],'cart':['./src/page/cart/index.js'],'order-confirm':['./src/page/order-confirm/index.js'],'order-list':['./src/page/order-list/index.js'],'order-detail':['./src/page/order-detail/index.js'],'payment':['./src/page/payment/index.js'],'user-login':['./src/page/user-login/index.js'],'user-register':['./src/page/user-register/index.js'],'user-pass-reset':['./src/page/user-pass-reset/index.js'],'user-pass-update':['./src/page/user-pass-update/index.js'],'user-center':['./src/page/user-center/index.js'],'user-center-update':['./src/page/user-center-update/index.js'],'result':['./src/page/result/index.js'],'about':['./src/page/about/index.js']},output: {// 绝对路径path: '/dist/',publicPath: '/dist/',filename: 'js/[name].js'},externals:{'jquery':'window.jQuery'},module: {loaders: [{test: /\.css$/,loader:  ExtractTextPlugin.extract("style-loader","css-loader")},{test: /\.(gif|png|jpg|woff|svg|eot|ttf)\??.*$/,loader:  'url-loader?limit=100&name=resource/[name].[ext]'}]},plugins:[// 独立通用模块到js/base.jsnew webpack.optimize.CommonsChunkPlugin({name:'common',filename: 'js/base.js'}),// 把css单独打包到文件里new ExtractTextPlugin("css/[name].css"),// html模板的处理new HtmlWebpackPlugin(getHtmlConfig('index','首页')),new HtmlWebpackPlugin(getHtmlConfig('list','商品列表')),new HtmlWebpackPlugin(getHtmlConfig('detail','商品详情')),new HtmlWebpackPlugin(getHtmlConfig('cart','购物车')),new HtmlWebpackPlugin(getHtmlConfig('order-confirm','订单确认')),new HtmlWebpackPlugin(getHtmlConfig('order-list','订单列表')),new HtmlWebpackPlugin(getHtmlConfig('order-detail','订单详情')),new HtmlWebpackPlugin(getHtmlConfig('payment','订单支付')),new HtmlWebpackPlugin(getHtmlConfig('user-login','用户登录')),new HtmlWebpackPlugin(getHtmlConfig('user-register','用户注册')),new HtmlWebpackPlugin(getHtmlConfig('user-pass-reset','找回密码')),new HtmlWebpackPlugin(getHtmlConfig('user-pass-update','找回密码')),new HtmlWebpackPlugin(getHtmlConfig('user-center','个人中心')),new HtmlWebpackPlugin(getHtmlConfig('user-center-update','修改个人信息')),new HtmlWebpackPlugin(getHtmlConfig('result','操作结果')),new HtmlWebpackPlugin(getHtmlConfig('about','关于MMall'))]};// 只有开发环境加这句话if('dev'=== WEBPACK_ENV){config.entry.common.push('webpack-dev-server/client?http://localhost:8088/');}module.exports  = config;
这里有前面没讲的一个细节如下
output: {// 绝对路径path: '/dist/',publicPath: '/dist/',filename: 'js/[name].js'},
注意path指的是打包生成的文件路径,publicPath指的是访问页面时文件的路径,publicPath必须要设置一下,否则访问页面时资源加载可能出问题最后如果大家觉得乱 或者不明白可以参考我的总代码:
/** @Author: zhang* @Date:   2017-05-08 15:28:19* @Last Modified by:   zhang* @Last Modified time: 2017-06-13 19:17:31*/var webpack             = require('webpack');var ExtractTextPlugin   = require('extract-text-webpack-plugin');var HtmlWebpackPlugin   = require('html-webpack-plugin');// 环境变量配置,dev / onlinevar WEBPACK_ENV         = process.env.WEBPACK_ENV || 'dev';// 获取html-webpack-plugin参数的方法var getHtmlConfig = function(name, title){return {template    : './src/view/' + name + '.html',filename    : 'view/' + name + '.html',favicon     : './favicon.ico',title       : title,inject      : true,hash        : true,chunks      : ['common', name]};};// webpack configvar config = {entry: {'common'            : ['./src/page/common/index.js'],'index'             : ['./src/page/index/index.js'],'list'              : ['./src/page/list/index.js'],'detail'            : ['./src/page/detail/index.js'],'cart'              : ['./src/page/cart/index.js'],'order-confirm'     : ['./src/page/order-confirm/index.js'],'order-list'        : ['./src/page/order-list/index.js'],'order-detail'      : ['./src/page/order-detail/index.js'],'payment'           : ['./src/page/payment/index.js'],'user-login'        : ['./src/page/user-login/index.js'],'user-register'     : ['./src/page/user-register/index.js'],'user-pass-reset'   : ['./src/page/user-pass-reset/index.js'],'user-center'       : ['./src/page/user-center/index.js'],'user-center-update': ['./src/page/user-center-update/index.js'],'user-pass-update'  : ['./src/page/user-pass-update/index.js'],'result'            : ['./src/page/result/index.js'],'about'             : ['./src/page/about/index.js'],},output: {path        : __dirname + '/dist/',publicPath  : 'dev' === WEBPACK_ENV ? '/dist/' : '//s.happymmall.com/mmall-fe/dist/',filename    : 'js/[name].js'},externals : {'jquery' : 'window.jQuery'},module: {loaders: [{ test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader","css-loader") },{ test: /\.(gif|png|jpg|woff|svg|eot|ttf)\??.*$/, loader: 'url-loader?limit=100&name=resource/[name].[ext]' },{test: /\.string$/,loader: 'html-loader',query : {minimize : true,removeAttributeQuotes : false}}]},resolve : {alias : {node_modules    : __dirname + '/node_modules',util            : __dirname + '/src/util',page            : __dirname + '/src/page',service         : __dirname + '/src/service',image           : __dirname + '/src/image'}},plugins: [// 独立通用模块到js/base.jsnew webpack.optimize.CommonsChunkPlugin({name : 'common',filename : 'js/base.js'}),// 把css单独打包到文件里new ExtractTextPlugin("css/[name].css"),// html模板的处理new HtmlWebpackPlugin(getHtmlConfig('index', '首页')),new HtmlWebpackPlugin(getHtmlConfig('list', '商品列表')),new HtmlWebpackPlugin(getHtmlConfig('detail', '商品详情')),new HtmlWebpackPlugin(getHtmlConfig('cart', '购物车')),new HtmlWebpackPlugin(getHtmlConfig('order-confirm', '订单确认')),new HtmlWebpackPlugin(getHtmlConfig('order-list', '订单列表')),new HtmlWebpackPlugin(getHtmlConfig('order-detail', '订单详情')),new HtmlWebpackPlugin(getHtmlConfig('payment', '订单支付')),new HtmlWebpackPlugin(getHtmlConfig('user-login', '用户登录')),new HtmlWebpackPlugin(getHtmlConfig('user-register', '用户注册')),new HtmlWebpackPlugin(getHtmlConfig('user-pass-reset', '找回密码')),new HtmlWebpackPlugin(getHtmlConfig('user-center', '个人中心')),new HtmlWebpackPlugin(getHtmlConfig('user-center-update', '修改个人信息')),new HtmlWebpackPlugin(getHtmlConfig('user-pass-update', '修改密码')),new HtmlWebpackPlugin(getHtmlConfig('result', '操作结果')),new HtmlWebpackPlugin(getHtmlConfig('about', '关于MMall')),]};if('dev' === WEBPACK_ENV){config.entry.common.push('webpack-dev-server/client?http://localhost:8088/');}module.exports = config;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息