webpack对js通用模块的封装

1、html渲染

npm install hogan --save

2、安装iconawesome字体

npm install font-awedsome --save

二、配置和html引用、css加载的使用方法

1、webpack.config.js设置

entry: {
        'common'               : ['./src/page/common/index.js'],
        'index'                : ['./src/page/index/index.js'], }, module:{  loaders: [ { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader","css-loader") }, { test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/, loader: 'url-loader?limit=50000&name=[path][name].[ext]'} ] }, resolve : { alias : { node_modules : __dirname + '/node_modules', util : __dirname + '/src/util', page : __dirname + '/src/page', service : __dirname + '/src/service', image : __dirname + '/src/image' } },

文件夹名字配置,html-loader方式渲染配置

2、page/common/index.js引入

require('./layout.css');
require('node_modules/font-awesome/css/font-awesome.min.css');

3、view/index.html页面中使用示例

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8" /> <%= require('html-loader!./layout/head-common.html') %> <title>电商平台</title> </head> <body> <%= require('html-loader!./layout/header.html') %> <%= require('html-loader!./layout/footer.html') %> </body> </html>

三、string、title的定制

1、webpack.config.js设置

var path              = require('path');
var webpack           = require('webpack'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var HtmlWebpackPlugin = require('html-webpack-plugin'); // 环境变量的设定 var WEBPACK_ENV = process.env.WEBPACK_ENV || 'dev_win'; console.log(WEBPACK_ENV); var getHtmlConfig=function (name,title) { return{ template :'./src/view/'+ name +'.html', filename :'view/'+ name +'.html', title : title, inject : true, hash : true, chunks : ['common',name] } } var config = {  entry: { 'common' : ['./src/page/common/index.js'], 'index' : ['./src/page/index/index.js'], 'user-login' : ['./src/page/user-login/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|jpg|png|woff|svg|eot|ttf)\??.*$/, loader: 'url-loader?limit=50000&name=[path][name].[ext]'}, { test: /\.string$/, loader: 'html-loader'} ] }, resolve : { alias : { node_modules : __dirname + '/node_modules', util : __dirname + '/src/util', page : __dirname + '/src/page', service : __dirname + '/src/service', image : __dirname + '/src/image' } },  plugins: [ new webpack.optimize.CommonsChunkPlugin({  name: 'common',  filename: 'js/base.js' }), new ExtractTextPlugin("css/[name].css"), new HtmlWebpackPlugin(getHtmlConfig('index','首页')), new HtmlWebpackPlugin(getHtmlConfig('user-login','用户登录')), ] }; if('dev_win'===WEBPACK_ENV){ config.entry.common.push('webpack-dev-server/client?http://localhost:8080/') } module.exports = config;

2、page/common/nav-side/index.string字符串

{{#navList}}

{{#isActive}} <li class="nav-item active"> {{/isActive}} {{^isActive}} <li class="nav-item"> {{/isActive}} <a href="{{href}}" class="link">{{desc}}</a> </li> {{/navList}}

3、page/common/nav-side/index.js(mm工具会在后面说明)

'use strict';
require('./index.css')

var _mm                 =  require('util/mm.js'); var templateIndex = require('./index.string'); // 导航 var navSide={ option : { name: '', navList:[ {name : 'user-center',desc:'个人中心',href:'./user-center.html'}, {name : 'order-list',desc:'我的订单',href:'./user-list.html'}, {name : 'pass-update',desc:'修改密码',href:'./pass-update.html'}, {name : 'about',desc:'关于MMall',href:'./about.html'} ] }, // // 渲染导航菜单 renderNav : function(){ for (var i = 0,iLength = this.option.navList.length;i<iLength;i++) { if(this.option.navList[i].name === this.option.name){ this.option.navList[i].isActive = true; } }; // 渲染list数据 var navHtml = _mm.renderHtml(templateIndex,{ navList : this.option.navList }); // // 把html放入容器 $('.nav-side').html(navHtml) }, init : function(option){ // 合并选项 $.extend(this.option,option); this.renderNav(); }, } module.exports = navSide;

4、view/index.html(css略)页面引入

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8" /> <%= require('html-loader!./layout/head-common.html') %> <title><%= htmlWebpackPlugin.options.title%>--happlmmall电商平台</title> </head> <body> <%= require('html-loader!./layout/nav.html') %> <%= require('html-loader!./layout/header.html') %> <%= require('html-loader!./layout/nav-side.html') %> <%= require('html-loader!./layout/footer.html') %> </body> </html>

四、mm通用工具

在util/mm.js下,包含ajax的数据请求,服务器地址的获取,url正则提取后的路径,html模板渲染的,成功、错误提示,字段的正则验证,对登录的统一处理等

'use strict';
var Hogan = require('hogan');
var conf={ serverHost:'' }; var _mm = { request : function (param) { var _this = this; $.ajax({ type : param.method || 'get', url : param.url || '', dataType: param.type || 'json', data : param.data || '', success : function (res) { // 请求成功 if(0 === res.status){ typeof param.success === 'function' && param.success(res.data,res.msg); } // 如果没有登录则强制返回 else if(10 === res.status){ _this.doLogin(); } // 请求数据错误 else if(1 === res.status){ typeof param.error === 'function' && param.error(res.msg) } }, error : function (err) { // body... typeof param.error === 'function' && param.error(err.statusText); } }) }, // 获取服务器地址 getServerUrl : function (path) { return conf.serverHost + path; }, getUrlParam : function (name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i"); var result = window.location.search.substr(1).match(reg); // return result ? result[2]:null return result ? decodeURIComponent(result[2]):null }, // 渲染html模板 renderHtml : function(htmlTemplate,data){ var template = Hogan.compile(htmlTemplate), result = template.render(data); // result = htmlTemplate.render(data); return result; }, // 成功提示 successTips : function(msg){ alert(msg || '操作成功!'); }, // 错误提示 errorTips : function(msg){ alert(msg || '哪里不对啦!') }, // 字段的验证,支持非空,手机,邮箱 validate : function(value,type){ if('require' === type){ // 网上查没什么区别,不晓得为嘛!!写法 return !!value; } if('phone' === type){ return /^1[34578]\d{9}$/.test(value); } if('email' === type){ return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value); } }, // 统一登录处理 doLogin : function () { window.location.href = './user-login.html?redirect=' + encodeURIComponent(window.location.href) }, goHome : function(){ window.location.href = './index.html'; } } module.exports = _mm;

四、样式布局(包含后面章节修改完整版)

引入css的方法

1、layout的整体样式示例:src/page/common/layout.css

*{
    margin: 0;
    padding: 0;
}
body{ background: #f6f6f6; font: 12px/1.5 tahoma,arial,Microsoft YaHei,sans-serif; } li{ list-style: none; } img{ display: block; border:none } label{ cursor:pointer; } button{border:none} input[type='checkbox']{ cursor:pointer } /* 定宽布局 */ .w{ width: 1080px; margin:0 auto; position: relative; overflow: hidden; } .large .w{ width:1600px } /* panel */ .panel{ padding: 10px; margin-bottom: 10px; background: #fff } .panel .panel-title{ padding: 10px; font-size: 14px; color: #666; font-weight: bold; border-bottom:1px solid #eee; } .panel .panel-body{ padding: 10px; overflow: hidden; } /* 全局通用样式 */ .hide{ display:none } .link{ color:#999; cursor:pointer; text-decoration: none; } .link:hover{ color:#e80012; } .link-text{ color:#999; text-decoration:none; } /* btn */ .btn{ display:inline-block; padding:0 20px; height:40px; line-height: 40px; vertical-align: middle; border:none; background:#c60023; font-size:17px; color:#fff; outline:none; cursor:pointer; text-decoration:none; } .btn-mini{ height:25px; line-height:25px; font-size:12px; padding:0 10px; } .loading{ margin:10px auto; display:block; width:65px; height:65px; border:1px solid #ddd; border-radius:5px; background:url(../../image/icon/loading.gif) no-repeat; background-size: 100%; opacity: 6; } 

2、src/page/commonnav-side/index.css样式

/* 导航主体 */
.nav-side{
    float: left;
    width: 130px; min-height: 100px; } .nav-side .nav-item{ line-height: 25px; font-size: 13px; } .nav-side .nav-item .link{ color: #888 } .nav-side .nav-item.active .link{ color:#c60023; } /* 右侧内容区 */ .content.with-nav{ float: left; width: 950px } 

猜你喜欢

转载自www.cnblogs.com/karry990921/p/8999338.html