UNPKG

@dafengzhen/vite-plugin-mp

Version:

vite-plugin-mp 使用 Vite 编译微信小程序

4 lines (3 loc) 8.18 kB
"use strict";const y=require("fs"),l=require("path"),v=require("tinyglobby"),w=require("vite"),j=require("crypto"),_="vite-plugin-mp-copy";function E(e={}){const o=e.rootDir??"miniprogram";let a=e.outputDir??"miniprogram";const r=e.debug??!1,t=e.targets??[];if(!Array.isArray(t))throw new Error('The "targets" option must be an array of objects with "src" and "dest" properties.');return{apply:"build",configResolved(n){var s;a=l.join(((s=n.build)==null?void 0:s.outDir)??"dist",a)},async generateBundle(){if(t.length===0)return;const n=l.resolve(o),s=l.resolve(a),i=m=>{r&&this.info(m)};i(`OutputDir: ${a}`);for(const m of t){const{dest:f,src:u}=m;(!u||!f)&&this.error('Each target must have both "src" and "dest" properties.');try{const c=await v.glob(u,{cwd:n});i(`Found ${c.length} files for pattern "${u}"`);const p=u.split("/")[0];i(`SrcBase: ${p}`);let d,h;for(const g of c){const $=l.join(n,g);!p||!g.startsWith(p)?d=g:d=l.relative(p,g),h=l.join(s,f,d),i(`Copying: ${g}`),i(`SrcPath: ${$}`),i(`DestPath: ${h}`),await y.promises.mkdir(l.dirname(h),{recursive:!0}),await y.promises.copyFile($,h)}}catch(c){this.error(`Failed to copy files from "${u}" to "${f}": ${c instanceof Error?c.message:String(c)}`)}}},name:_}}const x="vite-plugin-mp-entry";function A(){return{config(e){const o={build:{rollupOptions:{input:{[x]:x},onwarn:(a,r)=>{var n,s,i;if((n=a.names)!=null&&n.includes(x))return;const t=(i=(s=e.build)==null?void 0:s.rollupOptions)==null?void 0:i.onwarn;typeof t=="function"?t==null||t(a,r):t&&r(a)}}}};return w.mergeConfig(e,o)},generateBundle(e,o){for(const[a,r]of Object.entries(o))if(r.name===x){delete o[a];break}},load(e){return e===x?"":null},name:x,resolveId(e){return e===x?e:null}}}const C="vite-plugin-mp-json";function O(e={}){const o=e.rootDir??"miniprogram",a=e.outputDir??"miniprogram",r=e.jsonInclude,t=e.jsonIgnore,n=[];return{buildStart(){const s=[`${o}/**/*.json`,"project.config.json"];typeof r=="string"?s.push(r):Array.isArray(r)&&s.push(...r),n.push(...v.globSync(s,{ignore:t}))},async generateBundle(){try{await Promise.all(n.map(async s=>{try{const i=await y.promises.readFile(s,"utf-8"),m=JSON.parse(i),f=JSON.stringify(m),u=s.startsWith(o),c=u?l.relative(o,s):s,p=u?w.normalizePath(l.join(a,c)):c;this.emitFile({fileName:p,source:f,type:"asset"})}catch(i){this.warn(`Failed to process ${s}: ${i instanceof Error?i.message:i}`)}}))}catch(s){this.error(`Failed to find JSON files: ${s instanceof Error?s.message:s}`)}},name:C}}const I="vite-plugin-mp-tovw",k=(e,o=750)=>e.replace(/:\s*([^;{}]+)rpx/g,a=>a.replace(/(\d+(\.\d+)?)rpx/g,(r,t)=>`${(parseFloat(t)/o*100).toFixed(3)}vw`));function R(e={}){const o=e.rpxToVw??!1,a=e.designWidth??750;return{name:I,transform(r,t){return o&&t.endsWith(".css")&&r.includes("rpx")?{code:k(r,a),map:null}:null}}}const T="vite-plugin-mp-wxjs",b="wxjs-";function X(e={}){const o=e.rootDir??"miniprogram",a=e.outputDir??"miniprogram",r=e.isTsProject??!0?"ts":"js";return{config(t){var u,c,p;const s=v.globSync(`${o}/**/*.${r}`).reduce((d,h)=>{const g=l.relative(o,h).replace(r==="ts"?/\.ts$/:/\.js$/,""),$=j.createHash("md5").update(h).digest("hex").slice(0,8),B=`${b}${g}-${$}`;return d[B]=l.resolve(h),d},{}),i=(c=(u=t==null?void 0:t.build)==null?void 0:u.rollupOptions)==null?void 0:c.output,f={build:{assetsDir:((p=t==null?void 0:t.build)==null?void 0:p.assetsDir)??`${a}/assets`,rollupOptions:{input:s,output:{entryFileNames:d=>{const h=d.name;if(h.startsWith(b)){const $=h.substring(b.length).replace(/-\w{8}$/,".js");return w.normalizePath(l.join(a,$))}const g=i==null?void 0:i.entryFileNames;return typeof g=="function"?g(d):typeof g=="string"?g:"[name].js"},format:(i==null?void 0:i.format)??"cjs"}}}};return w.mergeConfig(t,f)},name:T,transform(t,n){if(!n.endsWith(`.${r}`))return null;const s=l.extname(n),i=l.basename(n,s),m=l.dirname(n),f=`${i}.wxml`,u=`${i}.wxss`,c=`${i}.json`,p=[];return y.existsSync(l.join(m,f))&&p.push(`import './${f}?raw';`),y.existsSync(l.join(m,u))&&p.push(`import './${u}?raw';`),y.existsSync(l.join(m,c))&&p.push(`import './${c}?raw';`),p.length===0?null:{code:`${p.join(` `)} ${t}`,id:n}}}}const P="vite-plugin-mp-wxml",F="wxml-",q=e=>Object.prototype.toString.call(e)==="[object Uint8Array]",z=e=>q(e)?{text:new TextDecoder("utf-8").decode(e),wasBinary:!0}:{text:e,wasBinary:!1},J=async(e,o,a)=>{const{text:r,wasBinary:t}=z(e);let n=U(r,o);if(typeof a=="function"){const s=a(t?new TextEncoder().encode(n):n);s instanceof Promise?n=await s:n=s}return n},U=(e,o)=>{const a=/<script\b[^>]*>([\s\S]*?)<\/script>/gi;return e.replaceAll(a,r=>o.some(t=>r.includes(t))?"":r)};function H(e={}){const o=e.rootDir??"miniprogram",a=e.outputDir??"miniprogram",r=e.compress,t=[];return{config(n){const m={build:{rollupOptions:{input:v.globSync(`${o}/**/*.wxml`).reduce((f,u)=>{const c=l.relative(o,u).replace(/\.wxml$/,""),p=j.createHash("md5").update(u).digest("hex").slice(0,8),d=`${F}${c}-${p}`;return t.push(`${d}.js`),f[d]=l.resolve(u),f},{}),plugins:[{async generateBundle(f,u){for(const[c,p]of Object.entries(u))if(p.type==="asset"&&c.endsWith(".html")){const d=l.relative(o,c).replace(/\.html$/,".wxml"),h=w.normalizePath(l.join(a,d));delete u[c];const g=await J(p.source,t,r);u[d]={...p,fileName:h,source:g}}else p.type==="chunk"&&c.endsWith(".js")&&c.startsWith(F)&&delete u[c]},name:"vite-plugin-html-rename"}]}}};return w.mergeConfig(n,m)},enforce:"pre",async load(n){if(!n.endsWith(".html"))return null;const s=n.replace(/\.html$/,".wxml");return{code:await y.promises.readFile(s,"utf-8"),map:null,meta:{customData:{now:Date.now(),sourceFile:s,type:"wxml"}}}},name:P,resolveId(n,s){if(!n.endsWith(".wxml"))return null;const i=s?l.dirname(s):process.cwd(),m=l.resolve(i,n);return{external:!1,id:m.replace(/\.wxml$/,".html"),meta:{customData:{fileName:m,now:Date.now(),type:"wxml"}},moduleSideEffects:!0,resolvedBy:P}}}}const M=(e=8)=>{const o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",a=j.randomBytes(e),r=new Array(e);for(let t=0;t<e;t++)r[t]=o[a[t]%o.length];return r.join("")},S="vite-plugin-mp-wxss",D="wxss-";function L(e={}){const o=e.rootDir??"miniprogram",a=e.outputDir??"miniprogram";return{config(r){const s={build:{rollupOptions:{input:v.globSync(`${o}/**/*.wxss`).reduce((i,m)=>{const f=l.relative(o,m).replace(/\.wxss$/,""),u=j.createHash("md5").update(m).digest("hex").slice(0,8),c=`${D}${f}-${u}`;return i[c]=l.resolve(m),i},{}),output:{assetFileNames:i=>{var u,c,p,d;const m=(u=i.names)==null?void 0:u[0];if(m!=null&&m.startsWith(D)){const h=m.substring(D.length).replace(/-\w{8}.css$/,".wxss");return w.normalizePath(l.join(a,h))}const f=(d=(p=(c=r==null?void 0:r.build)==null?void 0:c.rollupOptions)==null?void 0:p.output)==null?void 0:d.assetFileNames;return typeof f=="function"?f(i):typeof f=="string"?f:"assets/[name]-[hash][extname]"}}}}};return w.mergeConfig(r,s)},enforce:"pre",generateBundle(r,t){for(const[n,s]of Object.entries(t))if(s.type==="chunk"&&n.endsWith(".js")&&n.startsWith(D))delete t[n];else if(s.type==="asset"&&n.endsWith(".wxss")&&typeof s.source=="string"){const i=s.source.replace(/\.__wxss_[A-Za-z0-9]{8}__\s*\{\s*color:\s*#fff;?\s*}/gs,"");t[n]={...s,source:i}}},async load(r){if(!r.endsWith(".css"))return null;const t=r.replace(/\.css$/,".wxss");return{code:await y.promises.readFile(t,"utf-8"),map:null,meta:{customData:{now:Date.now(),sourceFile:t,type:"wxss"}}}},name:S,resolveId(r,t){if(!r.endsWith(".wxss"))return null;const n=t?l.dirname(t):process.cwd(),s=l.resolve(n,r);return{external:!1,id:s.replace(/\.wxss$/,".css"),meta:{customData:{fileName:s,now:Date.now(),type:"wxss"}},moduleSideEffects:!0,resolvedBy:S}},transform(r,t){return t.endsWith(".css")&&r?{code:r+`.__wxss_${M()}__ {color:#fff}`}:null}}}const W="vite-plugin-mp",V=`${W}-root-check`;function N(e={}){const o=e.rootDir??"miniprogram";return[G(o),A(),H(e),L(e),X(e),O(e),E(e),R(e)]}function G(e){return{async buildStart(){try{const o=l.resolve(e);(await y.promises.readdir(o)).length===0&&this.warn(`rootDir "${e}" is an empty directory.`)}catch(o){o.code==="ENOENT"?this.warn(`rootDir "${e}" does not exist.`):this.warn(`Failed to check rootDir "${e}": ${String(o)}`)}},name:V}}N.resolvedBy=W;module.exports=N;