更新
This commit is contained in:
+4
@@ -0,0 +1,4 @@
|
||||
import type { BuildOptions, UserConfig } from 'vite';
|
||||
export declare function buildOptions(): UserConfig['build'];
|
||||
export declare function createBuildOptions(inputDir: string, platform: UniApp.PLATFORM): BuildOptions;
|
||||
export declare function notFound(filename: string): never;
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.notFound = exports.createBuildOptions = exports.buildOptions = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const entry_1 = require("../plugins/entry");
|
||||
const debugChunk = (0, debug_1.default)('uni:chunk');
|
||||
function buildOptions() {
|
||||
const platform = process.env.UNI_PLATFORM;
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
const outputDir = process.env.UNI_OUTPUT_DIR;
|
||||
// 开始编译时,清空输出目录
|
||||
if (fs_1.default.existsSync(outputDir)) {
|
||||
(0, uni_cli_shared_1.emptyDir)(outputDir, ['project.config.json', 'project.private.config.json']);
|
||||
}
|
||||
return createBuildOptions(inputDir, platform);
|
||||
}
|
||||
exports.buildOptions = buildOptions;
|
||||
function createBuildOptions(inputDir, platform) {
|
||||
const { renderDynamicImport } = (0, uni_cli_shared_1.dynamicImportPolyfill)();
|
||||
return {
|
||||
// TODO 待优化,不同小程序平台sourcemap处理逻辑可能不同
|
||||
// TODO 目前存在两层sourcemap,一层是vite的,一层是小程序的,目前拿不到小程序的sourcemap,导致没法还原到源码,所以暂时不默认启用
|
||||
sourcemap: (0, uni_cli_shared_1.isEnableConsole)() && (0, uni_cli_shared_1.enableSourceMap)(),
|
||||
// target: ['chrome53'], // 由小程序自己启用 es6 编译
|
||||
emptyOutDir: false, // 不清空输出目录,否则会影响自定义的一些文件输出,比如wxml
|
||||
lib: process.env.UNI_COMPILE_TARGET === 'uni_modules'
|
||||
? false
|
||||
: {
|
||||
// 必须使用 lib 模式,否则会生成 preload 等代码
|
||||
fileName: 'app.js',
|
||||
entry: (0, uni_cli_shared_1.resolveMainPathOnce)(inputDir),
|
||||
formats: ['cjs'],
|
||||
},
|
||||
rollupOptions: {
|
||||
input: process.env.UNI_COMPILE_TARGET === 'uni_modules'
|
||||
? {}
|
||||
: parseRollupInput(inputDir, platform),
|
||||
output: {
|
||||
sourcemapPathTransform: (relativeSourcePath, sourcemapPath) => {
|
||||
const result = sourcemapPathTransform(relativeSourcePath, sourcemapPath);
|
||||
if (platform === 'mp-alipay') {
|
||||
return path_1.default.basename(result);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
entryFileNames(chunk) {
|
||||
if (chunk.name === 'main') {
|
||||
return 'app.js';
|
||||
}
|
||||
return chunk.name + '.js';
|
||||
},
|
||||
format: 'cjs',
|
||||
manualChunks: createMoveToVendorChunkFn(),
|
||||
chunkFileNames: createChunkFileNames(inputDir),
|
||||
plugins: [
|
||||
{
|
||||
name: 'dynamic-import-polyfill',
|
||||
renderDynamicImport(options) {
|
||||
const { targetModuleId } = options;
|
||||
if (targetModuleId && (0, uni_cli_shared_1.isMiniProgramAssetFile)(targetModuleId)) {
|
||||
return {
|
||||
left: 'Promise.resolve(require(',
|
||||
right: '))',
|
||||
};
|
||||
}
|
||||
return renderDynamicImport.call(this, options);
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.createBuildOptions = createBuildOptions;
|
||||
function sourcemapPathTransform(relativeSourcePath, sourcemapPath) {
|
||||
const prefix = '';
|
||||
let [, modulePath] = relativeSourcePath.split('/node_modules/');
|
||||
if (modulePath) {
|
||||
return `${prefix}node_modules/${modulePath}`;
|
||||
}
|
||||
let [, base64] = relativeSourcePath.split('/uniPage:/');
|
||||
if (base64) {
|
||||
return prefix + (0, entry_1.parseVirtualPagePath)(base64) + '?type=page';
|
||||
}
|
||||
;
|
||||
[, base64] = relativeSourcePath.split('/uniComponent:/');
|
||||
if (base64) {
|
||||
return prefix + (0, entry_1.parseVirtualComponentPath)(base64) + '?type=component';
|
||||
}
|
||||
return (prefix +
|
||||
(0, uni_cli_shared_1.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, path_1.default.resolve(path_1.default.dirname(sourcemapPath), relativeSourcePath))));
|
||||
}
|
||||
function parseRollupInput(inputDir, platform) {
|
||||
const inputOptions = {
|
||||
app: (0, uni_cli_shared_1.resolveMainPathOnce)(inputDir),
|
||||
};
|
||||
if (process.env.UNI_MP_PLUGIN) {
|
||||
return inputOptions;
|
||||
}
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir);
|
||||
const plugins = manifestJson[platform]?.plugins || {};
|
||||
Object.keys(plugins).forEach((name) => {
|
||||
const pluginExport = plugins[name].export;
|
||||
if (!pluginExport) {
|
||||
return;
|
||||
}
|
||||
const pluginExportFile = path_1.default.resolve(inputDir, pluginExport);
|
||||
if (!fs_1.default.existsSync(pluginExportFile)) {
|
||||
notFound(pluginExportFile);
|
||||
}
|
||||
inputOptions[(0, uni_cli_shared_1.removeExt)(pluginExport)] = pluginExportFile;
|
||||
});
|
||||
return inputOptions;
|
||||
}
|
||||
function isVueJs(id) {
|
||||
return id.includes('\0plugin-vue:export-helper');
|
||||
}
|
||||
const chunkFileNameBlackList = ['main', 'pages.json', 'manifest.json'];
|
||||
function createMoveToVendorChunkFn() {
|
||||
const cache = new Map();
|
||||
const inputDir = (0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR);
|
||||
return (id, { getModuleInfo }) => {
|
||||
const normalizedId = (0, uni_cli_shared_1.normalizePath)(id);
|
||||
const filename = normalizedId.split('?')[0];
|
||||
// 处理资源文件
|
||||
if (uni_cli_shared_1.DEFAULT_ASSETS_RE.test(filename)) {
|
||||
debugChunk('common/assets', normalizedId);
|
||||
return 'common/assets';
|
||||
}
|
||||
// 处理项目内的js,ts文件
|
||||
if (uni_cli_shared_1.EXTNAME_JS_RE.test(filename)) {
|
||||
if (filename.startsWith(inputDir) && !filename.includes('node_modules')) {
|
||||
const chunkFileName = (0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizePath)(path_1.default.relative(inputDir, filename)));
|
||||
if (!chunkFileNameBlackList.includes(chunkFileName) &&
|
||||
!(0, uni_cli_shared_1.hasJsonFile)(chunkFileName) // 无同名的page,component
|
||||
) {
|
||||
debugChunk(chunkFileName, normalizedId);
|
||||
return chunkFileName;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 非项目内的 js 资源,均打包到 vendor
|
||||
debugChunk('common/vendor', normalizedId);
|
||||
return 'common/vendor';
|
||||
}
|
||||
if (isVueJs(normalizedId) ||
|
||||
(normalizedId.includes('node_modules') &&
|
||||
!(0, uni_cli_shared_1.isCSSRequest)(normalizedId) &&
|
||||
// 使用原始路径,格式化的可能找不到模块信息 https://github.com/dcloudio/uni-app/issues/3425
|
||||
staticImportedByEntry(id, getModuleInfo, cache))) {
|
||||
debugChunk('common/vendor', id);
|
||||
return 'common/vendor';
|
||||
}
|
||||
};
|
||||
}
|
||||
function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
|
||||
if (cache.has(id)) {
|
||||
return cache.get(id);
|
||||
}
|
||||
if (importStack.includes(id)) {
|
||||
// circular deps!
|
||||
cache.set(id, false);
|
||||
return false;
|
||||
}
|
||||
const mod = getModuleInfo(id);
|
||||
if (!mod) {
|
||||
cache.set(id, false);
|
||||
return false;
|
||||
}
|
||||
if (mod.isEntry) {
|
||||
cache.set(id, true);
|
||||
return true;
|
||||
}
|
||||
const someImporterIs = mod.importers.some((importer) => staticImportedByEntry(importer, getModuleInfo, cache, importStack.concat(id)));
|
||||
cache.set(id, someImporterIs);
|
||||
return someImporterIs;
|
||||
}
|
||||
function createChunkFileNames(inputDir) {
|
||||
return function chunkFileNames(chunk) {
|
||||
if (chunk.isDynamicEntry && chunk.facadeModuleId) {
|
||||
let id = chunk.facadeModuleId;
|
||||
if ((0, entry_1.isUniPageUrl)(id)) {
|
||||
id = path_1.default.resolve(process.env.UNI_INPUT_DIR, (0, entry_1.parseVirtualPagePath)(id));
|
||||
}
|
||||
else if ((0, entry_1.isUniComponentUrl)(id)) {
|
||||
id = path_1.default.resolve(process.env.UNI_INPUT_DIR, (0, entry_1.parseVirtualComponentPath)(id));
|
||||
}
|
||||
return (0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeMiniProgramFilename)(id, inputDir)) + '.js';
|
||||
}
|
||||
return '[name].js';
|
||||
};
|
||||
}
|
||||
function notFound(filename) {
|
||||
console.log();
|
||||
console.error(uni_cli_shared_1.M['file.notfound'].replace('{file}', filename));
|
||||
console.log();
|
||||
process.exit(0);
|
||||
}
|
||||
exports.notFound = notFound;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { UniMiniProgramPluginOptions } from '.';
|
||||
export declare function createConfigResolved({ cdn, style: { extname }, template: { component }, }: UniMiniProgramPluginOptions): Plugin['configResolved'];
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createConfigResolved = void 0;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const pagesJson_1 = require("../plugins/pagesJson");
|
||||
const entry_1 = require("../plugins/entry");
|
||||
const debugNVueCss = (0, debug_1.default)('uni:nvue-css');
|
||||
const cssVars = `page{--status-bar-height:25px;--top-window-height:0px;--window-top:0px;--window-bottom:0px;--window-left:0px;--window-right:0px;--window-magin:0px}`;
|
||||
const uvueCssVars = `page{--status-bar-height:25px;--top-window-height:0px;--window-top:0px;--window-bottom:0px;--window-left:0px;--window-right:0px;--window-magin:0px;--uni-safe-area-inset-top:0px;--uni-safe-area-inset-left:0px;--uni-safe-area-inset-right:0px;--uni-safe-area-inset-bottom:0px;}`;
|
||||
const genShadowCss = (cdn) => {
|
||||
const url = (0, uni_cli_shared_1.createShadowImageUrl)(cdn, 'grey');
|
||||
return `page::after{position:fixed;content:'';left:-1000px;top:-1000px;-webkit-animation:shadow-preload .1s;-webkit-animation-delay:3s;animation:shadow-preload .1s;animation-delay:3s}@-webkit-keyframes shadow-preload{0%{background-image:url(${url})}100%{background-image:url(${url})}}@keyframes shadow-preload{0%{background-image:url(${url})}100%{background-image:url(${url})}}`;
|
||||
};
|
||||
const genComponentCustomHiddenCss = (name) => `[${name.replace(':', '')}="true"]{display: none !important;}`;
|
||||
function createConfigResolved({ cdn, style: { extname }, template: { component }, }) {
|
||||
function normalizeCssChunkFilename(id, extname) {
|
||||
return ((0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeMiniProgramFilename)(id, process.env.UNI_INPUT_DIR)) +
|
||||
extname);
|
||||
}
|
||||
return (config) => {
|
||||
const mainPath = (0, uni_cli_shared_1.resolveMainPathOnce)(process.env.UNI_INPUT_DIR);
|
||||
fixUnocss(config);
|
||||
(0, uni_cli_shared_1.injectCssPlugin)(config, process.env.UNI_COMPILE_TARGET === 'uni_modules'
|
||||
? {
|
||||
createUrlReplacer: uni_cli_shared_1.createEncryptCssUrlReplacer,
|
||||
}
|
||||
: {});
|
||||
let unocssGlobalBuildBundleIndex = config.plugins.findIndex((p) => p.name === 'unocss:global:build:bundle');
|
||||
if (unocssGlobalBuildBundleIndex === -1) {
|
||||
unocssGlobalBuildBundleIndex = config.plugins.findIndex((p) => p.name === 'unocss:global:build:generate');
|
||||
}
|
||||
const hasUnocssGlobalBuildBundle = unocssGlobalBuildBundleIndex > -1;
|
||||
// unocss 是根据 .css 后缀来编译文件,需要先保持 css 文件后缀为 .css,等 unocss 处理完后,再重置回正确的文件后缀
|
||||
const cssExtname = hasUnocssGlobalBuildBundle ? '.css' : extname;
|
||||
(0, uni_cli_shared_1.injectCssPostPlugin)(config, (0, uni_cli_shared_1.cssPostPlugin)(config, {
|
||||
platform: process.env.UNI_PLATFORM,
|
||||
chunkCssFilename(id) {
|
||||
if (id === mainPath) {
|
||||
return 'app' + cssExtname;
|
||||
}
|
||||
else if ((0, entry_1.isUniPageUrl)(id)) {
|
||||
return normalizeCssChunkFilename((0, entry_1.parseVirtualPagePath)(id), cssExtname);
|
||||
}
|
||||
else if ((0, entry_1.isUniComponentUrl)(id)) {
|
||||
return normalizeCssChunkFilename((0, entry_1.parseVirtualComponentPath)(id), cssExtname);
|
||||
}
|
||||
},
|
||||
chunkCssCode(filename, cssCode) {
|
||||
const isX = process.env.UNI_APP_X === 'true';
|
||||
cssCode = (0, uni_cli_shared_1.transformScopedCss)(cssCode);
|
||||
if (filename === 'app' + cssExtname) {
|
||||
const componentCustomHiddenCss = (component &&
|
||||
component.vShow &&
|
||||
genComponentCustomHiddenCss(component.vShow)) ||
|
||||
'';
|
||||
const realCssVars = isX ? uvueCssVars : cssVars;
|
||||
if (config.isProduction) {
|
||||
return (cssCode +
|
||||
genShadowCss(cdn || 0) +
|
||||
realCssVars +
|
||||
componentCustomHiddenCss);
|
||||
}
|
||||
else {
|
||||
return cssCode + realCssVars + componentCustomHiddenCss;
|
||||
}
|
||||
}
|
||||
if (isX) {
|
||||
if (component?.[':host']) {
|
||||
const flexDirection = (0, uni_cli_shared_1.parseUniXFlexDirection)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR));
|
||||
cssCode = `:host{display:flex;flex-direction:${flexDirection}}\n${cssCode}`;
|
||||
}
|
||||
if (!(0, uni_cli_shared_1.isMiniProgramPageFile)(filename)) {
|
||||
return cssCode;
|
||||
}
|
||||
/**
|
||||
* 此方法将subPackages中的页面合并到了pages内
|
||||
*/
|
||||
const pagesJson = (0, uni_cli_shared_1.parsePagesJsonOnce)(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM);
|
||||
const page = pagesJson.pages.find((page) => page.path === (0, uni_cli_shared_1.removeExt)(filename));
|
||||
if (!page) {
|
||||
return cssCode;
|
||||
}
|
||||
/**
|
||||
* 何时不重置样式?
|
||||
* - page.style.enabelUcssReset为false
|
||||
* - page.style.enableUcssReset为空,pagesJson.globalStyle.enableUcssReset为false
|
||||
* - page.style.enableUcssReset为空,pagesJson.globalStyle.enableUcssReset为空,page.style.renderer为skyline
|
||||
*/
|
||||
const shouldNotResetStyle = page.style.enableUcssReset === false ||
|
||||
(page.style.enableUcssReset == null &&
|
||||
pagesJson.globalStyle.enableUcssReset === false) ||
|
||||
(page.style.enableUcssReset == null &&
|
||||
pagesJson.globalStyle.enableUcssReset == null &&
|
||||
page.style.renderer === 'skyline');
|
||||
if (!shouldNotResetStyle) {
|
||||
/**
|
||||
* 兼容发布为小程序分包模式
|
||||
*/
|
||||
const uvueCssPath = (0, uni_cli_shared_1.relativeFile)(filename, `uvue${extname}`);
|
||||
cssCode = `@import "${uvueCssPath}";\n` + cssCode;
|
||||
}
|
||||
return cssCode;
|
||||
}
|
||||
const nvueCssPaths = (0, pagesJson_1.getNVueCssPaths)(config);
|
||||
if (!nvueCssPaths || !nvueCssPaths.length) {
|
||||
return cssCode;
|
||||
}
|
||||
const normalized = (0, uni_cli_shared_1.normalizePath)(filename);
|
||||
if (nvueCssPaths.find((pageCssPath) => pageCssPath === normalized)) {
|
||||
debugNVueCss(normalized);
|
||||
return (`@import "${(0, uni_cli_shared_1.relativeFile)(normalized, 'nvue' + extname)}";\n` +
|
||||
cssCode);
|
||||
}
|
||||
return cssCode;
|
||||
},
|
||||
}));
|
||||
(0, uni_cli_shared_1.injectAssetPlugin)(config);
|
||||
if (hasUnocssGlobalBuildBundle && extname !== '.css') {
|
||||
;
|
||||
config.plugins.splice(unocssGlobalBuildBundleIndex + 1, 0, adjustCssExtname(extname));
|
||||
}
|
||||
};
|
||||
}
|
||||
exports.createConfigResolved = createConfigResolved;
|
||||
function adjustCssExtname(extname) {
|
||||
return {
|
||||
name: 'uni:adjust-css-extname',
|
||||
generateBundle(_, bundle) {
|
||||
const files = Object.keys(bundle);
|
||||
files.forEach((name) => {
|
||||
if (name.endsWith('.css')) {
|
||||
const asset = bundle[name];
|
||||
(0, shared_1.isString)(asset.source) &&
|
||||
(asset.source = asset.source.replace(/\*\,/g, 'page,'));
|
||||
this.emitFile({
|
||||
fileName: name.replace('.css', extname),
|
||||
type: 'asset',
|
||||
source: asset.source,
|
||||
});
|
||||
delete bundle[name];
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
function fixUnocss(config) {
|
||||
const unocssGlobalBuildScan = config.plugins.find((p) => p.name === 'unocss:global:build:scan');
|
||||
// TODO 原始的 scan 的 buildStart 会清空 vfsLayerMap,导致 watch 时,load 阶段 /__uno.css 获取不到
|
||||
// https://github.com/antfu/unocss/blob/main/packages/vite/src/modes/global/build.ts#L25
|
||||
if (unocssGlobalBuildScan) {
|
||||
// 隐患: task 未被清空
|
||||
unocssGlobalBuildScan.buildStart = () => { };
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import type { AliasOptions } from 'vite';
|
||||
import { type AppJson, type CopyOptions, type MiniProgramCompilerOptions, type UniVitePlugin, type findMiniProgramTemplateFiles } from '@dcloudio/uni-cli-shared';
|
||||
import type { CompilerOptions } from '@dcloudio/uni-mp-compiler';
|
||||
export interface UniMiniProgramPluginOptions {
|
||||
cdn?: number;
|
||||
vite: {
|
||||
alias: AliasOptions;
|
||||
copyOptions: CopyOptions;
|
||||
inject: {
|
||||
[name: string]: [string, string];
|
||||
};
|
||||
};
|
||||
global: string;
|
||||
json?: {
|
||||
windowOptionsMap?: Record<string, string>;
|
||||
tabBarOptionsMap?: Record<string, string>;
|
||||
tabBarItemOptionsMap?: Record<string, string>;
|
||||
formatAppJson?: (appJson: Record<string, any>, manifestJson: Record<string, any>, pagesJson: Record<string, any>) => void;
|
||||
};
|
||||
app: {
|
||||
/**
|
||||
* 是否支持darkmode
|
||||
*/
|
||||
darkmode?: boolean;
|
||||
/**
|
||||
* 是否支持subpackages
|
||||
*/
|
||||
subpackages?: boolean;
|
||||
/**
|
||||
* 是否支持发行插件
|
||||
*/
|
||||
plugins?: boolean;
|
||||
/**
|
||||
* 是否支持全局组件
|
||||
*/
|
||||
usingComponents: boolean;
|
||||
normalize?: (appJson: AppJson) => AppJson;
|
||||
};
|
||||
project?: {
|
||||
filename: string;
|
||||
config: string[];
|
||||
source: Record<string, any>;
|
||||
normalize?: (projectJson: Record<string, unknown>) => Record<string, unknown>;
|
||||
};
|
||||
template: {
|
||||
extname: string;
|
||||
directive: string;
|
||||
event?: MiniProgramCompilerOptions['event'];
|
||||
class: MiniProgramCompilerOptions['class'];
|
||||
slot: MiniProgramCompilerOptions['slot'];
|
||||
lazyElement?: MiniProgramCompilerOptions['lazyElement'];
|
||||
component?: MiniProgramCompilerOptions['component'];
|
||||
customElements?: string[];
|
||||
filter?: {
|
||||
lang: string;
|
||||
extname: string;
|
||||
setStyle?: boolean;
|
||||
generate: Parameters<typeof findMiniProgramTemplateFiles>[0];
|
||||
};
|
||||
compilerOptions?: CompilerOptions;
|
||||
checkPropName?: MiniProgramCompilerOptions['checkPropName'];
|
||||
};
|
||||
style: {
|
||||
extname: string;
|
||||
};
|
||||
}
|
||||
export declare function uniMiniProgramPlugin(options: UniMiniProgramPluginOptions): UniVitePlugin;
|
||||
export declare function genUVueCssCode(manifestJson: Record<string, any>): string;
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.genUVueCssCode = exports.uniMiniProgramPlugin = void 0;
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const uni_1 = require("./uni");
|
||||
const build_1 = require("./build");
|
||||
const configResolved_1 = require("./configResolved");
|
||||
const template_1 = require("./template");
|
||||
const pagesJson_1 = require("../plugins/pagesJson");
|
||||
const polyfill_1 = require("./polyfill");
|
||||
function uniMiniProgramPlugin(options) {
|
||||
const { vite: { alias, copyOptions }, template, style, } = options;
|
||||
let resetCssEmitted = false;
|
||||
let autoImportFilterEmitted = false;
|
||||
let resolvedConfig;
|
||||
(0, polyfill_1.rewriteCompileScriptOnce)();
|
||||
(0, polyfill_1.rewriteCompilerSfcParseOnce)();
|
||||
return {
|
||||
name: 'uni:mp',
|
||||
uni: (0, uni_1.uniOptions)({
|
||||
copyOptions,
|
||||
customElements: template.customElements,
|
||||
miniProgram: {
|
||||
event: template.event,
|
||||
class: template.class,
|
||||
filter: template.filter
|
||||
? {
|
||||
lang: template.filter.lang,
|
||||
setStyle: template.filter.setStyle,
|
||||
generate: template.filter.generate,
|
||||
}
|
||||
: undefined,
|
||||
directive: template.directive,
|
||||
lazyElement: template.lazyElement,
|
||||
component: template.component,
|
||||
emitFile: template_1.emitFile,
|
||||
slot: template.slot,
|
||||
checkPropName: template.checkPropName,
|
||||
},
|
||||
compilerOptions: template.compilerOptions,
|
||||
}),
|
||||
config() {
|
||||
return {
|
||||
base: process.env.UNI_SUBPACKAGE
|
||||
? '/' + process.env.UNI_SUBPACKAGE + '/'
|
||||
: '/', // 编译为分包时以分包名为基础路径
|
||||
resolve: {
|
||||
alias: {
|
||||
vue: (0, uni_cli_shared_1.resolveBuiltIn)(`@dcloudio/uni-mp-vue/${process.env.UNI_APP_X === 'true' ? 'dist-x' : 'dist'}/vue.runtime.esm.js`),
|
||||
'@vue/devtools-api': (0, uni_cli_shared_1.resolveBuiltIn)('@dcloudio/uni-mp-vue'),
|
||||
'vue-i18n': (0, uni_cli_shared_1.resolveVueI18nRuntime)(),
|
||||
...alias,
|
||||
},
|
||||
preserveSymlinks: true,
|
||||
},
|
||||
css: {
|
||||
postcss: {
|
||||
plugins: (0, uni_cli_shared_1.initPostcssPlugin)({
|
||||
uniApp: (0, uni_cli_shared_1.parseRpx2UnitOnce)(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM),
|
||||
}),
|
||||
},
|
||||
},
|
||||
optimizeDeps: {
|
||||
noDiscovery: true,
|
||||
include: [],
|
||||
},
|
||||
build: (0, build_1.buildOptions)(),
|
||||
};
|
||||
},
|
||||
configResolved(config) {
|
||||
resolvedConfig = config;
|
||||
const plugin = config.plugins.find((p) => p.name === 'vite:vue');
|
||||
if (plugin?.api?.options) {
|
||||
plugin.api.options.devToolsEnabled = false;
|
||||
}
|
||||
return (0, configResolved_1.createConfigResolved)(options)(config);
|
||||
},
|
||||
generateBundle() {
|
||||
if (template.filter) {
|
||||
const extname = template.filter.extname;
|
||||
if (process.env.UNI_APP_X === 'true') {
|
||||
// 目前 mp-weixin(mp-qq)、mp-alipay(mp-dingtalk)、mp-toutiao(mp-lark)均支持视图层setStyle
|
||||
if (template.filter.setStyle && !autoImportFilterEmitted) {
|
||||
autoImportFilterEmitted = true;
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
// uniView.wxs文件在分包内的引用路径不对
|
||||
fileName: `common/uniView${extname}`,
|
||||
source: fs_extra_1.default.readFileSync(path_1.default.resolve(__dirname, '../../lib/filters/uniView.js'), 'utf8'),
|
||||
});
|
||||
}
|
||||
}
|
||||
const filterFiles = (0, template_1.getFilterFiles)(resolvedConfig, this.getModuleInfo);
|
||||
Object.keys(filterFiles).forEach((filename) => {
|
||||
const { code } = filterFiles[filename];
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: filename + extname,
|
||||
source: code,
|
||||
});
|
||||
});
|
||||
}
|
||||
const templateFiles = (0, template_1.getTemplateFiles)(template);
|
||||
Object.keys(templateFiles).forEach((filename) => {
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: filename + template.extname,
|
||||
source: templateFiles[filename],
|
||||
});
|
||||
});
|
||||
if (!resetCssEmitted) {
|
||||
if (process.env.UNI_APP_X === 'true') {
|
||||
resetCssEmitted = true;
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: 'uvue' + style.extname,
|
||||
source: genUVueCssCode((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR)),
|
||||
});
|
||||
}
|
||||
else {
|
||||
const nvueCssPaths = (0, pagesJson_1.getNVueCssPaths)(resolvedConfig);
|
||||
if (nvueCssPaths && nvueCssPaths.length) {
|
||||
resetCssEmitted = true;
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: 'nvue' + style.extname,
|
||||
source: (0, uni_cli_shared_1.genNVueCssCode)((0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR)),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniMiniProgramPlugin = uniMiniProgramPlugin;
|
||||
function genUVueCssCode(manifestJson) {
|
||||
let cssCode = fs_extra_1.default.readFileSync(path_1.default.resolve(__dirname, '../../lib/uvue.css'), 'utf8');
|
||||
const flexDirection = (0, uni_cli_shared_1.parseUniXFlexDirection)(manifestJson);
|
||||
if (flexDirection !== 'column') {
|
||||
cssCode = cssCode.replace('column', flexDirection);
|
||||
}
|
||||
return cssCode;
|
||||
}
|
||||
exports.genUVueCssCode = genUVueCssCode;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
export declare const rewriteCompileScriptOnce: typeof rewriteCompileScript;
|
||||
export declare const rewriteCompilerSfcParseOnce: typeof rewriteCompilerSfcParse;
|
||||
declare function rewriteCompileScript(): void;
|
||||
/**
|
||||
* 重写 parse,解决相同内容被缓存,未触发 template 编译的问题
|
||||
*/
|
||||
declare function rewriteCompilerSfcParse(): void;
|
||||
export {};
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.rewriteCompilerSfcParseOnce = exports.rewriteCompileScriptOnce = void 0;
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_shared_1 = require("@dcloudio/uni-shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
exports.rewriteCompileScriptOnce = (0, uni_shared_1.once)(rewriteCompileScript);
|
||||
exports.rewriteCompilerSfcParseOnce = (0, uni_shared_1.once)(rewriteCompilerSfcParse);
|
||||
function rewriteCompileScript() {
|
||||
const compiler = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-sfc'));
|
||||
const { compileScript, compileTemplate, compileStyle, compileStyleAsync } = compiler;
|
||||
compiler.compileStyle = (options) => {
|
||||
// https://github.com/dcloudio/uni-app/issues/4076
|
||||
options.isProd = true;
|
||||
return compileStyle(options);
|
||||
};
|
||||
compiler.compileStyleAsync = (options) => {
|
||||
// https://github.com/dcloudio/uni-app/issues/4076
|
||||
options.isProd = true;
|
||||
return compileStyleAsync(options);
|
||||
};
|
||||
// script-setup + v-bind
|
||||
compiler.compileScript = (sfc, options) => {
|
||||
if (options?.templateOptions?.compilerOptions) {
|
||||
;
|
||||
options.templateOptions.compilerOptions.bindingCssVars =
|
||||
sfc.cssVars || [];
|
||||
}
|
||||
// 强制生产模式,确保 cssVar 的生成使用 hash
|
||||
// https://github.com/dcloudio/uni-app/issues/4076
|
||||
// dev模式下,会生成:{ "83a5a03c-style.color": style.color}
|
||||
options.isProd = true;
|
||||
return compileScript(sfc, options);
|
||||
};
|
||||
// script + v-bind
|
||||
compiler.compileTemplate = (options) => {
|
||||
if (options?.compilerOptions) {
|
||||
;
|
||||
options.compilerOptions.bindingCssVars =
|
||||
options.ssrCssVars || [];
|
||||
}
|
||||
// 同上
|
||||
options.isProd = true;
|
||||
return compileTemplate(options);
|
||||
};
|
||||
}
|
||||
/**
|
||||
* 重写 parse,解决相同内容被缓存,未触发 template 编译的问题
|
||||
*/
|
||||
function rewriteCompilerSfcParse() {
|
||||
const compilerSfc = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-sfc'));
|
||||
const { parse } = compilerSfc;
|
||||
compilerSfc.parse = (source, options) => {
|
||||
const res = parse(source, options);
|
||||
// template 中,先<view>hello</view>,然后修改为<view></view>,再恢复为<view>hello</view>,
|
||||
// 此时因为 descriptor 被缓存,不会触发 compileTemplate,故 parse 时,每次生成一个全新的 descriptor
|
||||
// https://github.com/vitejs/vite/blob/v2.9.13/packages/plugin-vue/src/script.ts#L44
|
||||
// https://github.com/dcloudio/uni-app/issues/3685
|
||||
res.descriptor = (0, shared_1.extend)({}, res.descriptor);
|
||||
return res;
|
||||
};
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { EmittedFile, GetModuleInfo } from 'rollup';
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
import { type MiniProgramFilterOptions } from '@dcloudio/uni-cli-shared';
|
||||
import type { UniMiniProgramPluginOptions } from '.';
|
||||
export declare function getFilterFiles(resolvedConfig: ResolvedConfig, getModuleInfo: GetModuleInfo): Record<string, MiniProgramFilterOptions>;
|
||||
export declare function getTemplateFiles(template: UniMiniProgramPluginOptions['template']): Record<string, string>;
|
||||
export declare const emitFile: (emittedFile: EmittedFile) => string;
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.emitFile = exports.getTemplateFiles = exports.getFilterFiles = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const renderjs_1 = require("../plugins/renderjs");
|
||||
const debugTemplate = (0, debug_1.default)('uni:mp-template');
|
||||
function getFilterFiles(resolvedConfig, getModuleInfo) {
|
||||
const filters = Object.create(null);
|
||||
const filtersCache = (0, renderjs_1.getFiltersCache)(resolvedConfig);
|
||||
if (!filtersCache.length) {
|
||||
return filters;
|
||||
}
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
function addFilter(id, filter) {
|
||||
const templateFilename = (0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeMiniProgramFilename)(id, inputDir));
|
||||
(0, uni_cli_shared_1.addMiniProgramTemplateFilter)(templateFilename, filter);
|
||||
const filterFilename = (0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeMiniProgramFilename)(filter.id, inputDir));
|
||||
if (templateFilename !== filterFilename) {
|
||||
// 外链
|
||||
filter.src = filterFilename;
|
||||
filters[filterFilename] = filter;
|
||||
}
|
||||
}
|
||||
filtersCache.forEach((filter) => {
|
||||
const moduleInfo = getModuleInfo(filter.id);
|
||||
if (!moduleInfo) {
|
||||
return;
|
||||
}
|
||||
const { importers } = moduleInfo;
|
||||
if (!importers.length) {
|
||||
return;
|
||||
}
|
||||
importers.forEach((importer) => addFilter(importer, filter));
|
||||
});
|
||||
return filters;
|
||||
}
|
||||
exports.getFilterFiles = getFilterFiles;
|
||||
function getTemplateFiles(template) {
|
||||
const files = (0, uni_cli_shared_1.findMiniProgramTemplateFiles)(template.filter?.generate);
|
||||
(0, uni_cli_shared_1.clearMiniProgramTemplateFiles)();
|
||||
return files;
|
||||
}
|
||||
exports.getTemplateFiles = getTemplateFiles;
|
||||
const emitFile = (emittedFile) => {
|
||||
if (emittedFile.type === 'asset') {
|
||||
const filename = emittedFile.fileName;
|
||||
(0, uni_cli_shared_1.addMiniProgramTemplateFile)((0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeMiniProgramFilename)(path_1.default.relative(process.env.UNI_INPUT_DIR, filename))), emittedFile.source.toString());
|
||||
debugTemplate(filename);
|
||||
return filename;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
exports.emitFile = emitFile;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { type CopyOptions, type MiniProgramCompilerOptions, type UniVitePlugin } from '@dcloudio/uni-cli-shared';
|
||||
import type { CompilerOptions } from '@dcloudio/uni-mp-compiler';
|
||||
export declare function uniOptions({ copyOptions, miniProgram, customElements, compilerOptions, }: {
|
||||
customElements?: string[];
|
||||
copyOptions: CopyOptions;
|
||||
miniProgram: MiniProgramCompilerOptions;
|
||||
compilerOptions?: CompilerOptions;
|
||||
}): UniVitePlugin['uni'];
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniOptions = void 0;
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_shared_1 = require("@dcloudio/uni-shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const compiler = __importStar(require("@dcloudio/uni-mp-compiler"));
|
||||
function uniOptions({ copyOptions, miniProgram, customElements, compilerOptions, }) {
|
||||
const manifest = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
|
||||
const platformOptions = manifest[process.env.UNI_PLATFORM] || {};
|
||||
const isX = process.env.UNI_APP_X === 'true';
|
||||
const mergeVirtualHostAttributes = platformOptions.mergeVirtualHostAttributes != null
|
||||
? platformOptions.mergeVirtualHostAttributes
|
||||
: isX;
|
||||
return {
|
||||
copyOptions,
|
||||
compiler: compiler,
|
||||
compilerOptions: {
|
||||
root: process.env.UNI_INPUT_DIR,
|
||||
miniProgram: (0, shared_1.extend)({}, miniProgram, {
|
||||
component: (0, shared_1.extend)({}, miniProgram.component, {
|
||||
mergeVirtualHostAttributes,
|
||||
}),
|
||||
}),
|
||||
isNativeTag: isX ? uni_shared_1.isMiniProgramUVueNativeTag : uni_shared_1.isMiniProgramNativeTag,
|
||||
isCustomElement: (0, uni_shared_1.createIsCustomElement)(customElements),
|
||||
...compilerOptions,
|
||||
nodeTransforms: [
|
||||
uni_cli_shared_1.transformPageHead,
|
||||
...(compilerOptions?.nodeTransforms || []),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniOptions = uniOptions;
|
||||
Reference in New Issue
Block a user