UNPKG

mya-golang-template

Version:

Plugin for golang html/template template

104 lines (90 loc) 3.5 kB
/** * mya jinja 解决方案 * @dependance: mya-server-jina fis-optimizer-jinja-xss */ const path = require('path'); const STATIC_PATTERN = fis.get('STATIC_PATTERN'); const srcPath = fis.get("srcPath"); const extlang = require('./extlang'); function retMapPostpackager(ret) { const root = fis.project.getProjectPath(); const map = fis.file.wrap(path.join(root, fis.get('namespace') ? fis.get('namespace') + '-map.json' : 'map.json'));; map.setContent(JSON.stringify(ret.map, null, map.optimizer ? null : 4)); // ret.map 为静态资源映射表 ret.pkg[map.subpath] = map; } function addRequire(content, file, conf) { content += `\n{{ require "${file.subpath.slice(1)}" }}`; return content; } // wap:tplpath -> templatePublishPath/tplPath function adjustTmplPath(content, file, conf) { content = content.replace(/(\{\{\s*template\s+\")(\S+?)(\"(?:.+?)\}\})/g, function(match, p1, p2, p3) { return p1 + p2.replace(fis.get('namespace') + ':', fis.get('build.templatePublishPath').replace(/\$/, '') + '/') + p3; }); return content; } function handleCustomFuncs(content, file, conf) { content = content.replace(/\{\{\s*script\s*\}\}([\S\s]+?){\{\s*endscript\s*\}\}/g, function(match, code) { code = code.trim().replace(/\r?\n/g, '').replace(/"/g, '\\"'); return `{{ script "<script>${code}</script>" . }}`; }); content = content.replace(/\{\{\s*style\s*\}\}([\S\s]+?){\{\s*endstyle\s*\}\}/g, function (match, code) { code = code.trim().replace(/\r?\n/g, '').replace(/"/g, '\\"'); return `{{ style "${code}" . }}`; }); return content; } module.exports = function (fis, opt) { // fis.set('server.type', 'golang'); fis.set('settings.parser.babel-7.x', { noSourceMaps: true }); fis.match('*.html', { // 仅 html 文件开启同名依赖,依赖同名 css/js useSameNameRequire: true, useCache: false }); fis.match('/(**.html)', { useMap: true, preprocessor: [addRequire, extlang], postprocessor: [adjustTmplPath, handleCustomFuncs], optimizer: [ fis.plugin('html-minifier', { // 不处理自定义注释 ignoreCustomComments: [/^\s*(STYLE_PLACEHOLDER|SCRIPT_PLACEHOLDER)/], // 不处理 golang template 语法 ignoreCustomFragments: [/{{[\s\S]*?}}/, /{{\s*script[\s\S]*?endscript\s*}}/] }) ] }, true); fis.match('${namespace}-map.json', { release: '/template/mya_conf/$0' }); fis.match('::package', { postpackager: function createMap(ret) { retMapPostpackager(ret); } }); // deploy 不走 skip-packed 插件 fis.match('**', { deploy: fis.plugin('local-deliver') }); // 模板文件中的js不要使用 es6,因为模板文件可以传递变量,比如 init({{ rate|e }}),这种在编译时会报错 fis.match(`/${srcPath}/**.html:js`, { preprocessor: null, rExt: 'js', parser: null, optimizer: null }); const devRules = { '::package': { postpackager: function createMap(ret) { retMapPostpackager(ret); } }, }; ['develop', 'mock', 'prod'].forEach(function (media) { Object.keys(devRules).forEach(function (key) { fis.media(media).match(key, devRules[key], true); // 防止规则被覆盖 }); }); };