微信原生文档见 文档
社区有方案,是在style中写入
这里的方案是使用vite插件,在编译完成后,对目标插件进行代码注入 (仅适用vue3 + vite) , 目前运行在uniapp 微信小程序上
目录结构:
/project-config
componentPlaceholder
componentPlaceholder.js
vite.uni-component-placeholder.js
vite插件代码
/**
实现了 uni编译完成后 , 处理 componentPlaceholder
*/
var fs = require('fs');
var path = require('path');
class ProcessComponentPlaceholder{
constructor(){
this.destFolder = process.env.UNI_OUTPUT_DIR;
}
process(){
let dev_fold = process.env.UNI_INPUT_DIR;
let dir = dev_fold+"/project-config/componentPlaceHolder/"
let files = fs.readdirSync(dir, 'utf-8');
let fileMap = {}
files.some((f) => {
let p = dir + "/" + f;
let stat = fs.lstatSync(p);
if (!stat.isDirectory()) {
fileMap[f] = p;
}
})
this.processNodes(fileMap)
}
processNodes(fileMap){
console.log("处理异步组件引用componentPlaceHolder",fileMap)
for(let jsonFileName in fileMap){
let path = fileMap[jsonFileName];
if(!path.lastIndexOf(".js")<0)continue;
let obj = require(path);
// console.log("读componentPlaceHolder", obj)
this.processOneConfig(obj);
}
console.table("componentPlaceHolder处理完毕")
}
processOneConfig(config){
for(let f in config){ //某个配置文件
let weixinJSONFile = this.destFolder+f+".json";
fs.readFile(weixinJSONFile,'utf8',(err, data)=>{
if (err) {
return console.log('componentPlaceHolder文件读取失败,失败原因是:' + err)
}
let weixinJSON = JSON.parse(data);
// console.log("读componentPlaceHolder",weixinJSON);
//准备合并配置
let usingComponents = weixinJSON["usingComponents"]||{};
let componentPlaceholder = weixinJSON["componentPlaceholder"]||{};
let customConfig = config[f];
for(let tag in customConfig) {
let tagVal = customConfig[tag];
let path = tagVal.path;
let replace = tagVal.replace;
// console.log(weixinJSONFile+ " " +tag+" "+path )
if(!usingComponents[tag]){
usingComponents[tag]="../.."+path; //这里的双层目录有必要可能动态算相对层级,根据项目自身情况而定
}
if(!componentPlaceholder[tag]){
componentPlaceholder[tag] = replace;
}
}
weixinJSON.usingComponents = usingComponents;
weixinJSON.componentPlaceholder = componentPlaceholder;
fs.writeFileSync(weixinJSONFile, JSON.stringify(weixinJSON,null,4))
}) ;
}
}
}
export default (options)=> {
var name = 'vite-plugin-copy-uniapp_config';
return {
name: name,
enforce: 'post',
closeBundle:()=>{ //buildEnd之后运行
options.forEach(function(option) {
let processor = new ProcessComponentPlaceholder();
processor.process();
});
}
};
}
配置文件 componentPlaceholder.js 代码:
/**
配置:
{
"某个包的组件路径,不带.vue后缀":{
"组件名,一般为文件名不带.vue和路径":{
path:"引用某个包的组件路径,不带.vue后缀",
replace:"未加载完成时的替换组件,比如view或某个全局组件"
}
}
}
*/
module.exports = {
"/pages/index/index":{
"tabbar-me":{
path:"/package-my/pages/my/my",
replace:"view"
},
},
}
vite.config.js
import viteComponentPlaceHolder from "./project-config/vite.uni-component-placeholder.js"
plugins.push(viteComponentPlaceHolder([{}]))
export default defineConfig({
plugins
});
启动时会有日志
08:48:43.602 处理异步组件引用componentPlaceHolder {
08:48:43.609 'componentPlaceholder.js': '/project-config/componentPlaceHolder//componentPlaceholder.js'
08:48:43.610 }
0 个评论
要回复文章请先登录或注册