更新
This commit is contained in:
+10
@@ -0,0 +1,10 @@
|
||||
import type { SFCScriptCompileOptions } from '@vue/compiler-sfc';
|
||||
import { type UniMiniProgramPluginOptions } from './plugin';
|
||||
export { UniMiniProgramPluginOptions } from './plugin';
|
||||
declare const _default: (options: UniMiniProgramPluginOptions) => (import("vite").Plugin<any> | import("rollup").Plugin<any>[] | ((options: {
|
||||
vueOptions?: {
|
||||
script?: Partial<SFCScriptCompileOptions>;
|
||||
};
|
||||
}) => import("vite").Plugin<any>))[];
|
||||
export default _default;
|
||||
export declare function resolveMiniProgramRuntime(dirname: string, fileName: string): string;
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
"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;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.resolveMiniProgramRuntime = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const plugin_1 = require("./plugin");
|
||||
const usingComponents_1 = require("./plugins/usingComponents");
|
||||
const mainJs_1 = require("./plugins/mainJs");
|
||||
const manifestJson_1 = require("./plugins/manifestJson");
|
||||
const pagesJson_1 = require("./plugins/pagesJson");
|
||||
const entry_1 = require("./plugins/entry");
|
||||
const renderjs_1 = require("./plugins/renderjs");
|
||||
const runtimeHooks_1 = require("./plugins/runtimeHooks");
|
||||
const subpackage_1 = require("./plugins/subpackage");
|
||||
const plugin_2 = require("./plugins/plugin");
|
||||
const vueCompilerDom = __importStar(require("@vue/compiler-dom"));
|
||||
const uniCliShared = __importStar(require("@dcloudio/uni-cli-shared"));
|
||||
exports.default = (options) => {
|
||||
if (!options.app.subpackages) {
|
||||
delete process.env.UNI_SUBPACKAGE;
|
||||
}
|
||||
if (!options.app.plugins) {
|
||||
delete process.env.UNI_MP_PLUGIN;
|
||||
}
|
||||
const normalizeComponentName = options.template.component?.normalizeName;
|
||||
const sourceMapDir = (0, uni_cli_shared_1.resolveSourceMapPath)(process.env.UNI_OUTPUT_DIR, process.env.UNI_PLATFORM);
|
||||
return [
|
||||
...((0, uni_cli_shared_1.isEnableConsole)() ? [(0, uni_cli_shared_1.uniHBuilderXConsolePlugin)('uni.__f__')] : []),
|
||||
...(process.env.UNI_APP_X === 'true'
|
||||
? [
|
||||
(0, uni_cli_shared_1.uniDecryptUniModulesPlugin)(),
|
||||
(0, uni_cli_shared_1.uniUTSUVueJavaScriptPlugin)(),
|
||||
(0, uni_cli_shared_1.resolveUTSCompiler)().uts2js({
|
||||
inputDir: process.env.UNI_INPUT_DIR,
|
||||
version: process.env.UNI_COMPILER_VERSION,
|
||||
cacheRoot: path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, '.uts2js/cache'),
|
||||
modules: {
|
||||
vueCompilerDom,
|
||||
uniCliShared,
|
||||
},
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(process.env.UNI_COMPILE_TARGET === 'uni_modules'
|
||||
? []
|
||||
: [
|
||||
() => {
|
||||
return (0, mainJs_1.uniMainJsPlugin)({
|
||||
normalizeComponentName,
|
||||
babelParserPlugins: ['typescript'],
|
||||
});
|
||||
},
|
||||
(0, manifestJson_1.uniManifestJsonPlugin)(options),
|
||||
(0, pagesJson_1.uniPagesJsonPlugin)(options),
|
||||
]),
|
||||
(0, entry_1.uniEntryPlugin)(options),
|
||||
(0, uni_cli_shared_1.uniViteInjectPlugin)('uni:mp-inject', (0, shared_1.extend)({ exclude: [/uni.api.esm/, /uni.mp.esm/] }, options.vite.inject)),
|
||||
(0, renderjs_1.uniRenderjsPlugin)({ lang: options.template.filter?.lang }),
|
||||
(0, runtimeHooks_1.uniRuntimeHooksPlugin)(),
|
||||
(0, plugin_1.uniMiniProgramPlugin)(options),
|
||||
(options) => {
|
||||
return (0, usingComponents_1.uniUsingComponentsPlugin)({
|
||||
normalizeComponentName,
|
||||
babelParserPlugins: options.vueOptions?.script?.babelParserPlugins,
|
||||
});
|
||||
},
|
||||
...(process.env.UNI_SUBPACKAGE ? [(0, subpackage_1.uniSubpackagePlugin)(options)] : []),
|
||||
...(process.env.UNI_MP_PLUGIN ? [(0, plugin_2.uniMiniProgramPluginPlugin)(options)] : []),
|
||||
...(process.env.UNI_COMPILE_TARGET === 'uni_modules'
|
||||
? [(0, uni_cli_shared_1.uniEncryptUniModulesAssetsPlugin)(), (0, uni_cli_shared_1.uniEncryptUniModulesPlugin)()]
|
||||
: []),
|
||||
(0, uni_cli_shared_1.uniSourceMapPlugin)({
|
||||
sourceMapDir,
|
||||
relativeSourceMapDir: (0, uni_cli_shared_1.normalizePath)(path_1.default.relative(path_1.default.dirname(process.env.UNI_OUTPUT_DIR), sourceMapDir)),
|
||||
}),
|
||||
];
|
||||
};
|
||||
function resolveMiniProgramRuntime(dirname, fileName) {
|
||||
if (process.env.UNI_APP_X === 'true') {
|
||||
return path_1.default.resolve(dirname, `../dist-x/${fileName}`);
|
||||
}
|
||||
return path_1.default.resolve(dirname, `${fileName}`);
|
||||
}
|
||||
exports.resolveMiniProgramRuntime = resolveMiniProgramRuntime;
|
||||
+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;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { UniMiniProgramPluginOptions } from '../plugin';
|
||||
export declare function virtualPagePath(filepath: string): string;
|
||||
export declare function virtualComponentPath(filepath: string): string;
|
||||
export declare function parseVirtualPagePath(uniPageUrl: string): string;
|
||||
export declare function parseVirtualComponentPath(uniComponentUrl: string): string;
|
||||
export declare function isUniPageUrl(id: string): boolean;
|
||||
export declare function isUniComponentUrl(id: string): boolean;
|
||||
export declare function uniEntryPlugin({ global, }: UniMiniProgramPluginOptions): Plugin;
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniEntryPlugin = exports.isUniComponentUrl = exports.isUniPageUrl = exports.parseVirtualComponentPath = exports.parseVirtualPagePath = exports.virtualComponentPath = exports.virtualPagePath = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const uniPagePrefix = 'uniPage://';
|
||||
const uniComponentPrefix = 'uniComponent://';
|
||||
function virtualPagePath(filepath) {
|
||||
return uniPagePrefix + (0, uni_cli_shared_1.encodeBase64Url)(filepath);
|
||||
}
|
||||
exports.virtualPagePath = virtualPagePath;
|
||||
function virtualComponentPath(filepath) {
|
||||
return uniComponentPrefix + (0, uni_cli_shared_1.encodeBase64Url)(filepath);
|
||||
}
|
||||
exports.virtualComponentPath = virtualComponentPath;
|
||||
function parseVirtualPagePath(uniPageUrl) {
|
||||
return (0, uni_cli_shared_1.decodeBase64Url)(uniPageUrl.replace(uniPagePrefix, ''));
|
||||
}
|
||||
exports.parseVirtualPagePath = parseVirtualPagePath;
|
||||
function parseVirtualComponentPath(uniComponentUrl) {
|
||||
return (0, uni_cli_shared_1.decodeBase64Url)(uniComponentUrl.replace(uniComponentPrefix, ''));
|
||||
}
|
||||
exports.parseVirtualComponentPath = parseVirtualComponentPath;
|
||||
function isUniPageUrl(id) {
|
||||
return id.startsWith(uniPagePrefix);
|
||||
}
|
||||
exports.isUniPageUrl = isUniPageUrl;
|
||||
function isUniComponentUrl(id) {
|
||||
return id.startsWith(uniComponentPrefix);
|
||||
}
|
||||
exports.isUniComponentUrl = isUniComponentUrl;
|
||||
const styleIsolationRE = /export\s+default\s+[\s\S]*?styleIsolation\s*:\s*['|"](isolated|apply-shared|shared)['|"]/;
|
||||
function parseComponentStyleIsolation(file) {
|
||||
const content = fs_1.default.readFileSync(file, 'utf-8');
|
||||
const matches = content.match(styleIsolationRE);
|
||||
if (matches) {
|
||||
return matches[1];
|
||||
}
|
||||
}
|
||||
function uniEntryPlugin({ global, }) {
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir);
|
||||
const platformOptions = manifestJson[process.env.UNI_PLATFORM] || {};
|
||||
return {
|
||||
name: 'uni:virtual',
|
||||
enforce: 'pre',
|
||||
resolveId(id) {
|
||||
if (isUniPageUrl(id) || isUniComponentUrl(id)) {
|
||||
return id;
|
||||
}
|
||||
},
|
||||
load(id) {
|
||||
if (isUniPageUrl(id)) {
|
||||
const filepath = (0, uni_cli_shared_1.normalizePath)(path_1.default.resolve(inputDir, parseVirtualPagePath(id)));
|
||||
this.addWatchFile(filepath);
|
||||
return {
|
||||
code: `import MiniProgramPage from '${filepath}'
|
||||
${global}.createPage(MiniProgramPage)`,
|
||||
};
|
||||
}
|
||||
else if (isUniComponentUrl(id)) {
|
||||
const filepath = (0, uni_cli_shared_1.normalizePath)(path_1.default.resolve(inputDir, parseVirtualComponentPath(id)));
|
||||
this.addWatchFile(filepath);
|
||||
const json = {
|
||||
component: true,
|
||||
styleIsolation: undefined,
|
||||
};
|
||||
if (process.env.UNI_PLATFORM === 'mp-alipay') {
|
||||
json.styleIsolation =
|
||||
parseComponentStyleIsolation(filepath) ||
|
||||
platformOptions.styleIsolation ||
|
||||
'apply-shared';
|
||||
}
|
||||
// 微信小程序json文件中的styleIsolation优先级比options中的高,为了兼容旧版本,不能设置默认值,并且只有在manifest.json中配置styleIsolation才会静态分析组件的styleIsolation
|
||||
if (process.env.UNI_PLATFORM === 'mp-weixin') {
|
||||
if (platformOptions.styleIsolation) {
|
||||
json.styleIsolation =
|
||||
parseComponentStyleIsolation(filepath) ||
|
||||
platformOptions.styleIsolation;
|
||||
}
|
||||
}
|
||||
(0, uni_cli_shared_1.addMiniProgramComponentJson)((0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeMiniProgramFilename)(filepath, inputDir)), json);
|
||||
return {
|
||||
code: `import Component from '${filepath}'
|
||||
${global}.createComponent(Component)`,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniEntryPlugin = uniEntryPlugin;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type { SFCScriptCompileOptions } from '@vue/compiler-sfc';
|
||||
export declare function uniMainJsPlugin(options?: {
|
||||
normalizeComponentName?: (name: string) => string;
|
||||
babelParserPlugins?: SFCScriptCompileOptions['babelParserPlugins'];
|
||||
}): import("vite").Plugin<any>;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniMainJsPlugin = void 0;
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const usingComponents_1 = require("./usingComponents");
|
||||
function uniMainJsPlugin(options = {}) {
|
||||
const normalizeComponentName = options.normalizeComponentName || ((name) => name);
|
||||
return (0, uni_cli_shared_1.defineUniMainJsPlugin)((opts) => {
|
||||
return {
|
||||
name: 'uni:mp-main-js',
|
||||
enforce: 'pre',
|
||||
async transform(source, id) {
|
||||
if (opts.filter(id)) {
|
||||
source = source.includes('createSSRApp')
|
||||
? createApp(source)
|
||||
: createLegacyApp(source);
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
const { imports } = await (0, uni_cli_shared_1.updateMiniProgramGlobalComponents)(id, (0, uni_cli_shared_1.parseProgram)(source, id, {
|
||||
babelParserPlugins: options.babelParserPlugins,
|
||||
}), {
|
||||
inputDir,
|
||||
resolve: this.resolve,
|
||||
normalizeComponentName,
|
||||
});
|
||||
const { code, map } = await (0, uni_cli_shared_1.transformDynamicImports)(source, imports, {
|
||||
id,
|
||||
sourceMap: (0, uni_cli_shared_1.enableSourceMap)(),
|
||||
dynamicImport: usingComponents_1.dynamicImport,
|
||||
});
|
||||
return {
|
||||
code: `import '\0plugin-vue:export-helper';import 'uni-mp-runtime';import './${uni_cli_shared_1.PAGES_JSON_JS}';` +
|
||||
code,
|
||||
map,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
exports.uniMainJsPlugin = uniMainJsPlugin;
|
||||
function createApp(code) {
|
||||
return `${code};\ncreateApp().app.mount("#app");`;
|
||||
}
|
||||
function createLegacyApp(code) {
|
||||
return code;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { UniMiniProgramPluginOptions } from '../plugin';
|
||||
export declare function uniManifestJsonPlugin(options: UniMiniProgramPluginOptions): Plugin;
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniManifestJsonPlugin = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function findUserProjectConfigFile(inputDir, config) {
|
||||
for (let i = 0; i < config.length; i++) {
|
||||
const projectFilename = path_1.default.resolve(inputDir, config[i]);
|
||||
// 根目录包含指定文件,则直接拷贝
|
||||
if (fs_1.default.existsSync(projectFilename)) {
|
||||
return projectFilename;
|
||||
}
|
||||
}
|
||||
}
|
||||
function uniManifestJsonPlugin(options) {
|
||||
return (0, uni_cli_shared_1.defineUniManifestJsonPlugin)((opts) => {
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
const platform = process.env.UNI_PLATFORM;
|
||||
let projectJson;
|
||||
let userProjectFilename;
|
||||
let projectSource;
|
||||
if (options.project) {
|
||||
userProjectFilename = findUserProjectConfigFile(inputDir, options.project.config);
|
||||
}
|
||||
return {
|
||||
name: 'uni:mp-manifest-json',
|
||||
enforce: 'pre',
|
||||
transform(code, id) {
|
||||
if (!opts.filter(id)) {
|
||||
return;
|
||||
}
|
||||
this.addWatchFile(path_1.default.resolve(inputDir, 'manifest.json'));
|
||||
(0, uni_cli_shared_1.getLocaleFiles)(path_1.default.resolve(inputDir, 'locale')).forEach((filepath) => {
|
||||
this.addWatchFile(filepath);
|
||||
});
|
||||
if (options.project) {
|
||||
// 根目录包含指定文件,则直接拷贝
|
||||
if (userProjectFilename) {
|
||||
this.addWatchFile(userProjectFilename);
|
||||
projectJson = (0, uni_cli_shared_1.parseJson)(fs_1.default.readFileSync(userProjectFilename, 'utf8'), false, userProjectFilename);
|
||||
}
|
||||
else {
|
||||
const template = options.project.source;
|
||||
if ((0, shared_1.hasOwn)(template, 'appid')) {
|
||||
let projectName = path_1.default.basename(inputDir);
|
||||
if (projectName === 'src') {
|
||||
projectName = path_1.default.basename(path_1.default.dirname(inputDir));
|
||||
}
|
||||
template.projectname = projectName;
|
||||
// TODO condition
|
||||
if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
|
||||
if (!template.setting) {
|
||||
template.setting = {};
|
||||
}
|
||||
template.setting.urlCheck = false;
|
||||
}
|
||||
projectJson = (0, uni_cli_shared_1.parseMiniProgramProjectJson)(code, platform, {
|
||||
template,
|
||||
pagesJson: (0, uni_cli_shared_1.parsePagesJsonOnce)(inputDir, platform),
|
||||
});
|
||||
}
|
||||
else {
|
||||
// 无需解析,直接拷贝,如 quickapp-webview
|
||||
projectJson = template;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
code: '',
|
||||
map: { mappings: '' },
|
||||
};
|
||||
},
|
||||
generateBundle() {
|
||||
if (projectJson && options.project) {
|
||||
const { filename, normalize } = options.project;
|
||||
const source = JSON.stringify(normalize ? normalize(projectJson) : projectJson, null, 2);
|
||||
if (projectSource !== source) {
|
||||
projectSource = source;
|
||||
this.emitFile({
|
||||
fileName: filename,
|
||||
type: 'asset',
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
exports.uniManifestJsonPlugin = uniManifestJsonPlugin;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
import type { UniMiniProgramPluginOptions } from '../plugin';
|
||||
export declare function getNVueCssPaths(config: ResolvedConfig): string[] | undefined;
|
||||
export declare function uniPagesJsonPlugin(options: UniMiniProgramPluginOptions): Plugin;
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniPagesJsonPlugin = exports.getNVueCssPaths = 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 entry_1 = require("./entry");
|
||||
const uni_i18n_1 = require("@dcloudio/uni-i18n");
|
||||
const debugPagesJson = (0, debug_1.default)('uni:pages-json');
|
||||
const nvueCssPathsCache = new Map();
|
||||
function getNVueCssPaths(config) {
|
||||
return nvueCssPathsCache.get(config);
|
||||
}
|
||||
exports.getNVueCssPaths = getNVueCssPaths;
|
||||
function uniPagesJsonPlugin(options) {
|
||||
let resolvedConfig;
|
||||
const platform = process.env.UNI_PLATFORM;
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
return (0, uni_cli_shared_1.defineUniPagesJsonPlugin)((opts) => {
|
||||
let allPagePaths = [];
|
||||
let isFirst = true;
|
||||
return {
|
||||
name: 'uni:mp-pages-json',
|
||||
enforce: 'pre',
|
||||
configResolved(config) {
|
||||
resolvedConfig = config;
|
||||
},
|
||||
transform(code, id) {
|
||||
if (process.env.UNI_APP_X === 'true') {
|
||||
if (isFirst && allPagePaths.length) {
|
||||
const { filename } = (0, uni_cli_shared_1.parseVueRequest)(id);
|
||||
if (filename.endsWith('.vue') || filename.endsWith('.uvue')) {
|
||||
const vueFilename = (0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, filename)));
|
||||
// 项目内的
|
||||
if (!vueFilename.startsWith('.')) {
|
||||
// const index = allPagePaths.indexOf(pagePath)
|
||||
// if (index > -1) {
|
||||
if ((0, uni_cli_shared_1.runByHBuilderX)()) {
|
||||
console.log(`当前工程${allPagePaths.length}个页面,正在编译${vueFilename}...${'\u200b'}`);
|
||||
}
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!opts.filter(id)) {
|
||||
return null;
|
||||
}
|
||||
this.addWatchFile(path_1.default.resolve(inputDir, 'pages.json'));
|
||||
(0, uni_cli_shared_1.getLocaleFiles)(path_1.default.resolve(inputDir, 'locale')).forEach((filepath) => {
|
||||
this.addWatchFile(filepath);
|
||||
});
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir);
|
||||
const { appJson, pageJsons, nvuePages } = (0, uni_cli_shared_1.parseMiniProgramPagesJson)(code, platform, {
|
||||
debug: !!manifestJson.debug,
|
||||
darkmode: options.app.darkmode,
|
||||
networkTimeout: manifestJson.networkTimeout,
|
||||
subpackages: !!options.app.subpackages,
|
||||
...options.json,
|
||||
});
|
||||
nvueCssPathsCache.set(resolvedConfig, nvuePages.map((pagePath) => pagePath + options.style.extname));
|
||||
// add source
|
||||
(0, uni_cli_shared_1.mergeMiniProgramAppJson)(appJson, manifestJson[platform], options.project?.source ?? {});
|
||||
if (options.json?.formatAppJson) {
|
||||
options.json.formatAppJson(appJson, manifestJson, pageJsons);
|
||||
}
|
||||
// 使用 once 获取的话,可以节省编译时间,但 i18n 内容发生变化时,pages.json 不会自动更新
|
||||
const i18nOptions = (0, uni_cli_shared_1.initI18nOptionsOnce)(platform, inputDir, false, true);
|
||||
if (i18nOptions) {
|
||||
const { locale, locales, delimiters } = i18nOptions;
|
||||
(0, uni_i18n_1.parseI18nJson)(appJson, locales[locale], delimiters);
|
||||
(0, uni_i18n_1.parseI18nJson)(pageJsons, locales[locale], delimiters);
|
||||
}
|
||||
const { normalize } = options.app;
|
||||
(0, uni_cli_shared_1.addMiniProgramAppJson)(normalize ? normalize(appJson) : appJson);
|
||||
Object.keys(pageJsons).forEach((name) => {
|
||||
if (isNormalPage(name)) {
|
||||
(0, uni_cli_shared_1.addMiniProgramPageJson)(name, pageJsons[name]);
|
||||
allPagePaths.push(name);
|
||||
}
|
||||
});
|
||||
return {
|
||||
code: `import './${uni_cli_shared_1.MANIFEST_JSON_JS}'\n` + importPagesCode(appJson),
|
||||
map: { mappings: '' },
|
||||
};
|
||||
},
|
||||
generateBundle() {
|
||||
(0, uni_cli_shared_1.findChangedJsonFiles)(options.app.usingComponents).forEach((value, key) => {
|
||||
debugPagesJson('json.changed', key);
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: key + '.json',
|
||||
source: value,
|
||||
});
|
||||
});
|
||||
},
|
||||
buildEnd() {
|
||||
isFirst = false;
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
exports.uniPagesJsonPlugin = uniPagesJsonPlugin;
|
||||
/**
|
||||
* 字节跳动小程序可以配置 ext:// 开头的插件页面模板,如 ext://microapp-trade-plugin/order-confirm
|
||||
* @param pagePath
|
||||
* @returns
|
||||
*/
|
||||
function isNormalPage(pagePath) {
|
||||
return !pagePath.startsWith('ext://');
|
||||
}
|
||||
function importPagesCode(pagesJson) {
|
||||
const importPagesCode = [];
|
||||
function importPageCode(pagePath) {
|
||||
if (!isNormalPage(pagePath)) {
|
||||
return;
|
||||
}
|
||||
const pagePathWithExtname = (0, uni_cli_shared_1.normalizePagePath)(pagePath, process.env.UNI_PLATFORM);
|
||||
if (pagePathWithExtname) {
|
||||
importPagesCode.push(`import('${(0, entry_1.virtualPagePath)(pagePathWithExtname)}')`);
|
||||
}
|
||||
}
|
||||
pagesJson.pages.forEach((pagePath) => importPageCode(pagePath));
|
||||
if (pagesJson.subPackages) {
|
||||
pagesJson.subPackages.forEach(({ root, pages }) => {
|
||||
pages &&
|
||||
pages.forEach((pagePath) => importPageCode(path_1.default.join(root, pagePath)));
|
||||
});
|
||||
}
|
||||
return `if(!Math){
|
||||
${importPagesCode.join('\n')}
|
||||
}`;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { UniMiniProgramPluginOptions } from '../plugin';
|
||||
export declare function uniMiniProgramPluginPlugin({ style: { extname }, }: UniMiniProgramPluginOptions): Plugin;
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniMiniProgramPluginPlugin = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const subpackage_1 = require("./subpackage");
|
||||
const shared_1 = require("@vue/shared");
|
||||
const build_1 = require("../plugin/build");
|
||||
function uniMiniProgramPluginPlugin({ style: { extname }, }) {
|
||||
const entry = initPluginEntry();
|
||||
const rollupOptions = {};
|
||||
if (entry) {
|
||||
rollupOptions.input = (0, shared_1.extend)({
|
||||
app: (0, uni_cli_shared_1.resolveMainPathOnce)(process.env.UNI_INPUT_DIR),
|
||||
}, entry);
|
||||
}
|
||||
return {
|
||||
name: 'uni:mp-plugin',
|
||||
enforce: 'post',
|
||||
config() {
|
||||
return {
|
||||
build: {
|
||||
rollupOptions,
|
||||
},
|
||||
};
|
||||
},
|
||||
generateBundle: (0, subpackage_1.createNonAppGenerateBundle)(extname),
|
||||
};
|
||||
}
|
||||
exports.uniMiniProgramPluginPlugin = uniMiniProgramPluginPlugin;
|
||||
function initPluginEntry() {
|
||||
const pluginJsonFilename = path_1.default.resolve(process.env.UNI_INPUT_DIR, uni_cli_shared_1.MP_PLUGIN_JSON_NAME);
|
||||
if (!fs_1.default.existsSync(pluginJsonFilename)) {
|
||||
(0, build_1.notFound)(pluginJsonFilename);
|
||||
}
|
||||
const pluginJson = (0, uni_cli_shared_1.parseJson)(fs_1.default.readFileSync(pluginJsonFilename, 'utf8'), true, pluginJsonFilename);
|
||||
if (!pluginJson.main) {
|
||||
return;
|
||||
}
|
||||
const mainFilename = path_1.default.resolve(process.env.UNI_INPUT_DIR, pluginJson.main);
|
||||
if (!fs_1.default.existsSync(mainFilename)) {
|
||||
(0, build_1.notFound)(mainFilename);
|
||||
}
|
||||
return {
|
||||
[(0, uni_cli_shared_1.removeExt)(pluginJson.main)]: mainFilename,
|
||||
};
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
import { type MiniProgramFilterOptions } from '@dcloudio/uni-cli-shared';
|
||||
export declare function getFiltersCache(resolvedConfig: ResolvedConfig): MiniProgramFilterOptions[];
|
||||
export declare function uniRenderjsPlugin({ lang }: {
|
||||
lang?: string;
|
||||
}): Plugin;
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniRenderjsPlugin = exports.getFiltersCache = void 0;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const debugRenderjs = (0, debug_1.default)('uni:mp-renderjs');
|
||||
const filtersCache = new Map();
|
||||
function getFiltersCache(resolvedConfig) {
|
||||
return filtersCache.get(resolvedConfig) || [];
|
||||
}
|
||||
exports.getFiltersCache = getFiltersCache;
|
||||
function uniRenderjsPlugin({ lang }) {
|
||||
let resolvedConfig;
|
||||
return {
|
||||
name: 'uni:mp-renderjs',
|
||||
configResolved(config) {
|
||||
resolvedConfig = config;
|
||||
filtersCache.set(resolvedConfig, []);
|
||||
},
|
||||
transform(code, id) {
|
||||
const { type, name } = (0, uni_cli_shared_1.parseRenderjs)(id);
|
||||
if (!type) {
|
||||
return null;
|
||||
}
|
||||
debugRenderjs(id);
|
||||
if (type !== lang) {
|
||||
return {
|
||||
code: 'export default {}',
|
||||
map: { mappings: '' },
|
||||
};
|
||||
}
|
||||
this.addWatchFile((0, uni_cli_shared_1.cleanUrl)(id));
|
||||
if (!name) {
|
||||
this.error((0, uni_cli_shared_1.missingModuleName)(type, code));
|
||||
}
|
||||
else {
|
||||
let cache = filtersCache.get(resolvedConfig);
|
||||
if (cache) {
|
||||
const index = cache.findIndex((item) => item.id === id);
|
||||
if (index > -1) {
|
||||
cache.splice(index, 1);
|
||||
}
|
||||
cache.push({
|
||||
id,
|
||||
type,
|
||||
name,
|
||||
code,
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
code: (0, uni_cli_shared_1.genWxsCallMethodsCode)(code),
|
||||
map: { mappings: '' },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniRenderjsPlugin = uniRenderjsPlugin;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniRuntimeHooksPlugin(): Plugin;
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniRuntimeHooksPlugin = void 0;
|
||||
const uni_shared_1 = require("@dcloudio/uni-shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const compiler_sfc_1 = require("@vue/compiler-sfc");
|
||||
function uniRuntimeHooksPlugin() {
|
||||
return {
|
||||
name: 'uni:mp-runtime-hooks',
|
||||
enforce: 'post',
|
||||
async transform(source, id) {
|
||||
const isSetupJs = (0, uni_cli_shared_1.isUniPageSfcFile)(id);
|
||||
const isSetupTs = !isSetupJs && (0, uni_cli_shared_1.isUniPageSetupAndTs)(id);
|
||||
const isSetupUts = !isSetupJs && (0, uni_cli_shared_1.isUniPageSetupAndUts)(id);
|
||||
const isTypedSetup = isSetupTs || isSetupUts;
|
||||
if (!isSetupJs && !isSetupTs && !isSetupUts) {
|
||||
return null;
|
||||
}
|
||||
if (isSetupJs && !source.includes('_sfc_main')) {
|
||||
return null;
|
||||
}
|
||||
if (isTypedSetup && !source.includes('defineComponent')) {
|
||||
return null;
|
||||
}
|
||||
const matches = source.match(new RegExp(`(${Object.keys(uni_shared_1.MINI_PROGRAM_PAGE_RUNTIME_HOOKS).join('|')})`, 'g'));
|
||||
if (!matches) {
|
||||
return null;
|
||||
}
|
||||
if (matches.includes('onShareTimeline')) {
|
||||
matches.push('onShareAppMessage');
|
||||
}
|
||||
const hooks = new Set(matches);
|
||||
let flag = 0;
|
||||
for (const hook of hooks) {
|
||||
flag |= uni_shared_1.MINI_PROGRAM_PAGE_RUNTIME_HOOKS[hook];
|
||||
}
|
||||
if (isSetupJs) {
|
||||
source = source + `;_sfc_main.__runtimeHooks = ${flag};`;
|
||||
}
|
||||
else if (isTypedSetup) {
|
||||
source =
|
||||
require('@vue/compiler-sfc').rewriteDefault(source, '_sfc_defineComponent') +
|
||||
`\n_sfc_defineComponent.__runtimeHooks = ${flag};\nexport default _sfc_defineComponent`;
|
||||
}
|
||||
return {
|
||||
code: source,
|
||||
map: (0, uni_cli_shared_1.enableSourceMap)()
|
||||
? new compiler_sfc_1.MagicString(source).generateMap()
|
||||
: { mappings: '' },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniRuntimeHooksPlugin = uniRuntimeHooksPlugin;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { UniMiniProgramPluginOptions } from '../plugin';
|
||||
export declare function uniSubpackagePlugin({ style: { extname }, }: UniMiniProgramPluginOptions): Plugin;
|
||||
export declare function createNonAppGenerateBundle(extname: string): Plugin['generateBundle'];
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createNonAppGenerateBundle = exports.uniSubpackagePlugin = void 0;
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function uniSubpackagePlugin({ style: { extname }, }) {
|
||||
return {
|
||||
name: 'uni:mp-subpackage',
|
||||
enforce: 'post',
|
||||
generateBundle: createNonAppGenerateBundle(extname),
|
||||
};
|
||||
}
|
||||
exports.uniSubpackagePlugin = uniSubpackagePlugin;
|
||||
function createNonAppGenerateBundle(extname) {
|
||||
return function generateBundle(_, bundle) {
|
||||
;
|
||||
['project.config.json', 'app.json'].forEach((name) => {
|
||||
delete bundle[name];
|
||||
});
|
||||
const appJsFile = 'app.js';
|
||||
const appCssFile = 'app' + extname;
|
||||
Object.keys(bundle).forEach((name) => {
|
||||
if (!(0, uni_cli_shared_1.isMiniProgramPageFile)(name)) {
|
||||
return;
|
||||
}
|
||||
// 仅页面级 wxss 需要补充 app.wxss
|
||||
if (name.endsWith(extname)) {
|
||||
const cssFile = bundle[name];
|
||||
cssFile.source =
|
||||
`@import "${(0, uni_cli_shared_1.relativeFile)(name, appCssFile)}";\n` +
|
||||
cssFile.source.toString();
|
||||
}
|
||||
else if (name.endsWith('.js')) {
|
||||
const jsFile = bundle[name];
|
||||
jsFile.code =
|
||||
`require('${(0, uni_cli_shared_1.relativeFile)(name, appJsFile)}');\n` + jsFile.code;
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
exports.createNonAppGenerateBundle = createNonAppGenerateBundle;
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { SFCScriptCompileOptions } from '@vue/compiler-sfc';
|
||||
export declare function uniUsingComponentsPlugin(options?: {
|
||||
normalizeComponentName?: (name: string) => string;
|
||||
babelParserPlugins?: SFCScriptCompileOptions['babelParserPlugins'];
|
||||
}): Plugin;
|
||||
export declare function dynamicImport(name: string, value: string): string;
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.dynamicImport = exports.uniUsingComponentsPlugin = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const entry_1 = require("./entry");
|
||||
function uniUsingComponentsPlugin(options = {}) {
|
||||
const normalizeComponentName = options.normalizeComponentName || ((name) => name);
|
||||
const parseAst = (source, id) => {
|
||||
return (0, uni_cli_shared_1.parseProgram)(source, id, {
|
||||
babelParserPlugins: options.babelParserPlugins,
|
||||
});
|
||||
};
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
return {
|
||||
name: 'uni:mp-using-component',
|
||||
enforce: 'post',
|
||||
async transform(source, id) {
|
||||
const { filename, query } = (0, uni_cli_shared_1.parseVueRequest)(id);
|
||||
if ((0, uni_cli_shared_1.isAppVue)(filename)) {
|
||||
return null;
|
||||
}
|
||||
const sourceMap = (0, uni_cli_shared_1.enableSourceMap)();
|
||||
const dynamicImportOptions = {
|
||||
id,
|
||||
sourceMap,
|
||||
dynamicImport,
|
||||
};
|
||||
const resolve = async (source, importer, options) => {
|
||||
const id = (0, uni_cli_shared_1.resolveUTSModule)(source, importer || process.env.UNI_INPUT_DIR);
|
||||
if (id) {
|
||||
source = id;
|
||||
}
|
||||
return this.resolve(source, importer, options);
|
||||
};
|
||||
if (query.vue) {
|
||||
if (query.type === 'script') {
|
||||
// 需要主动监听
|
||||
this.addWatchFile(filename);
|
||||
const descriptor = await (0, uni_cli_shared_1.parseScriptDescriptor)(filename, parseAst(source, id), {
|
||||
resolve,
|
||||
isExternal: true,
|
||||
});
|
||||
(0, uni_cli_shared_1.updateMiniProgramComponentsByScriptFilename)(filename, inputDir, normalizeComponentName);
|
||||
return (0, uni_cli_shared_1.transformDynamicImports)(source, descriptor.imports, dynamicImportOptions);
|
||||
}
|
||||
else if (query.type === 'template') {
|
||||
// 需要主动监听
|
||||
this.addWatchFile(filename);
|
||||
const descriptor = await (0, uni_cli_shared_1.parseTemplateDescriptor)(filename, parseAst(source, id), {
|
||||
resolve,
|
||||
isExternal: true,
|
||||
});
|
||||
(0, uni_cli_shared_1.updateMiniProgramComponentsByTemplateFilename)(filename, inputDir, normalizeComponentName);
|
||||
return (0, uni_cli_shared_1.transformDynamicImports)(source, descriptor.imports, dynamicImportOptions);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!uni_cli_shared_1.EXTNAME_VUE.includes(path_1.default.extname(filename))) {
|
||||
return null;
|
||||
}
|
||||
const ast = parseAst(source, id);
|
||||
const descriptor = await (0, uni_cli_shared_1.parseMainDescriptor)(filename, ast, resolve);
|
||||
(0, uni_cli_shared_1.updateMiniProgramComponentsByMainFilename)(filename, inputDir, normalizeComponentName);
|
||||
return (0, uni_cli_shared_1.transformDynamicImports)(source, descriptor.imports, dynamicImportOptions);
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniUsingComponentsPlugin = uniUsingComponentsPlugin;
|
||||
function dynamicImport(name, value) {
|
||||
// 开发者可能将页面作为组件来引用
|
||||
if ((0, uni_cli_shared_1.isMiniProgramPageFile)(value, process.env.UNI_INPUT_DIR)) {
|
||||
return `const ${name} = ()=>import('${(0, entry_1.virtualPagePath)(value)}')`;
|
||||
}
|
||||
return `const ${name} = ()=>import('${(0, entry_1.virtualComponentPath)(value)}')`;
|
||||
}
|
||||
exports.dynamicImport = dynamicImport;
|
||||
Reference in New Issue
Block a user