1.2.3 • Published 4 years ago
mini_app_base_module v1.2.3
小程序与业务无关的基础组件
接入baseApplication的效果: 1. 可对所有的页面的生命周期做代理。 2. 可对setData方法的调用做控制。 3. 等等
在glup中添加以下任务:
// 为页面中统一引入基础组件,但暂时只有页面中引入,组件可以视情况单独写脚本引入
export const compilePageScript = () => {
return src(sources.pageScript)
.pipe($.changed('dist', { extension: '.js' }))
// 将所有的以Page(开头的字符串替换为MFPage
.pipe($.replace(/(\s+Page\(){1}/g, function (match, p1, offset, string) {
return '\n\nMFPage('
}))
// 替换setData方法
.pipe($.replace(/(.setData){1}/g, '.setMFData'))
// 由于业务中引入了redux,所以需要先进行混入
.pipe($.replace(new RegExp('[)][(]pageConfig[)]', 'g'), ')(mixin(pageConfig))'))
// 在每个文件头部添加相对路径引用
.pipe(gulpPrefixer({
relativePath: '/dist/mini_app_base_module/baseApplication.js',
prefixText: (relativePath) => `import { MFPage, mixin } from '${relativePath}'\n\n`
}))
.pipe(dest('dist/pages'))
}
compilePageScript.description = 'compile page script.'
在每个文件的头部会自动引入:
import { MFPage, mixin } from '../../../mini_app_base_module/baseApplication.js'
在头部引入import gulpPrefixer from './gulp-add-mf'
// gulp-add-mf.js
// through2 是一个对 node 的 transform streams 简单封装
var through = require('through2');
var path = require('path')
// 插件级别函数 (处理文件)
function gulpPrefixer(config) {
return through.obj(function (file, enc, cb) {
// 这个路径只能取相对路径
const relativePath = path.relative(file.dirname, file.cwd + config.relativePath);
if (file.isNull()) {
// 返回空文件
cb(null, file);
}
// 只有页面中包含有'MFPage才需要追加'
if (file.isBuffer()) {
file.contents = Buffer.concat([new Buffer(config.prefixText(relativePath)), file.contents]);
}
cb(null, file);
});
};
// 暴露(export)插件主函数
export default gulpPrefixer;