requirejs + vue 项目搭建详解

以前都是支持 司徒正美 的,毕竟咱们也是跟着 司徒正美 一起走进了前端的世界。所以一般MVVM都是用avalon的,当然也是考虑到项目需要支持IE6,7,8的考虑。当然在用的时候也有一些小坑和bug,都处理了。今年正美正好升级avalon2.0,加入虚拟dom的时候,不稳定了,就考试寻找其他的mvvm框架。

看了比较流行的一些框架,最后选择了vue。选择他的原因是 文档比较全,而且还有中文的(你懂的),生态圈比较好,有vux, vue-loader, vue-router ,组件化设计的也很好。

项目搭建的时候主要还是通过requirejs进行js模块加载(还没接触webpack,以前都是avalon+requirejs,习惯性思维了,下面就写写心路历程吧)

方案1,考虑能不能通过写个 requirejs 插件进行vue组件文件的加载

失败,主要是vue组件文件有template,script,style标签标签,主要通过requirejs,读取vue文件string文件进行正则分析在转换js, 有点舍近求远的方法,而且这种方式只能同域名ajax请求

方案2,通过编写gulp插件,将vue文件转换为可以通过requirejs加载的js文件。

这个方案是可行的,只是template,script,style信息,需要通过正则匹配,在动态载入到当前文档中,只是有些公用方法频繁调用。

所以加入了vueComment文件,把动态加入的方法整理在一起

define(['Vue'], function (Vue) { Vue.appendHTML = function (text) { document.body.insertAdjacentHTML('beforeEnd', text); }; var style; var doc = document; Vue.appendCSS = function (text) { text = text + " "; if (!style) { var head = doc.getElementsByTagName("head")[0]; var elms = head.getElementsByTagName("style"); if (elms.length == 0) { if (doc.createStyleSheet) { doc.createStyleSheet(); } else { var tmp = doc.createElement('style'); tmp.setAttribute("type", "text/css"); head.appendChild(tmp); } elms[0].setAttribute("media", "screen"); } style = elms[0]; } if (style.styleSheet) { style.styleSheet.cssText += text; } else if(doc.getBoxObjectFor) { style.innerHTML += text; } else { style.appendChild(doc.createTextNode(text)) } };    });

gulp-vue nodejs主要代码如下,通过文件名,来确定组件名字

var through = require('through2'); var gutil = require('gulp-util'); var regTpl = /<template>([\s\S]+?)<\/template>/; var regStyle = /<style>([\s\S]+?)<\/style>/; var regJs = /<script>([\s\S]+?)<\/script>/; var reg = [/'/g, /\n/g, /([^\\]+)\.vue$/]; var vueWrite = function (file, str) { var match = file.path.match(reg[2]); var id = "vue-tpl-" + match[1]; var appendJs = ""; var res = ""; str = str.replace(regTpl, function (t, h) { appendJs += "\tVue.appendHTML(\n'<template id=\"" + id + "\">" + h.replace(reg[0], "\\'").replace(reg[1], "\\\n") + "<\/template>');\n"; return ""; }).replace(regStyle, function (t, h) { appendJs += "\tVue.appendCSS(\n'" + h.replace(reg[0], "\\'").trim().replace(reg[1], "\\\n") + "');\n" return ""; }).replace(regJs, function (t, h) { res = "define(function (require) {\n\trequire('VueCommon'); \n\tvar Vue = require('Vue');\n\tvar exports;\n" + appendJs + h + ";\n\texports.template = '#" + id + "';\n\texports = Vue.extend(exports);\n\tVue.component('" + match[1] + "', exports);\n\treturn exports;\n});" return ; }) return res; }; module.exports = function(opt){ function run (file, encoding, callback) { if (file.isNull()) { return callback(null, file); } if (file.isStream()) { return callback(new gutil.PluginError('gulp-vue', 'doesn\'t support Streams')); } file.contents = new Buffer(vueWrite(file, file.contents.toString())); file.path = file.path + '.js'; callback(null, file); } return through.obj(run); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyxwsd.html