更新
This commit is contained in:
+3
@@ -0,0 +1,3 @@
|
||||
import type { Options } from 'unplugin-auto-import/types';
|
||||
export type AutoImportOptions = Options;
|
||||
export declare function initAutoImportOptions(platform: typeof process.env.UNI_UTS_PLATFORM, { imports, ...userOptions }: AutoImportOptions): AutoImportOptions;
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initAutoImportOptions = void 0;
|
||||
const uni_shared_1 = require("@dcloudio/uni-shared");
|
||||
const uts_1 = require("../uts");
|
||||
const uniPreset = {
|
||||
from: '@dcloudio/uni-app',
|
||||
imports: [
|
||||
// ssr
|
||||
'ssrRef',
|
||||
'shallowSsrRef',
|
||||
// uni-app lifecycle
|
||||
// App and Page
|
||||
'onShow',
|
||||
'onHide',
|
||||
// App
|
||||
'onLaunch',
|
||||
'onError',
|
||||
'onThemeChange',
|
||||
'onKeyboardHeightChange',
|
||||
'onPageNotFound',
|
||||
'onUnhandledRejection',
|
||||
'onLastPageBackPress',
|
||||
'onExit',
|
||||
// Page
|
||||
'onPageShow',
|
||||
'onPageHide',
|
||||
'onLoad',
|
||||
'onReady',
|
||||
'onUnload',
|
||||
'onResize',
|
||||
'onBackPress',
|
||||
'onPageScroll',
|
||||
'onTabItemTap',
|
||||
'onReachBottom',
|
||||
'onPullDownRefresh',
|
||||
// 其他
|
||||
'onShareTimeline',
|
||||
'onShareAppMessage',
|
||||
'onShareChat', // xhs-share
|
||||
// 辅助
|
||||
'renderComponentSlot',
|
||||
],
|
||||
};
|
||||
const uniH5Preset = {
|
||||
from: '@dcloudio/uni-h5',
|
||||
imports: [
|
||||
'onAppShow',
|
||||
'onAppHide',
|
||||
'offAppHide',
|
||||
'offAppShow',
|
||||
'UniElement',
|
||||
'UniElementImpl',
|
||||
'UniButtonElement',
|
||||
'UniCanvasElement',
|
||||
'UniCheckboxElement',
|
||||
'UniCheckboxGroupElement',
|
||||
'UniEditorElement',
|
||||
'UniFormElement',
|
||||
'UniIconElement',
|
||||
'UniImageElement',
|
||||
'UniInputElement',
|
||||
'UniLabelElement',
|
||||
'UniMovableAreaElement',
|
||||
'UniMovableViewElement',
|
||||
'UniNavigatorElement',
|
||||
'UniPickerViewElement',
|
||||
'UniPickerViewColumnElement',
|
||||
'UniProgressElement',
|
||||
'UniRadioElement',
|
||||
'UniRadioGroupElement',
|
||||
'UniRichTextElement',
|
||||
'UniScrollViewElement',
|
||||
'UniSliderElement',
|
||||
'UniSwiperElement',
|
||||
'UniSwiperItemElement',
|
||||
'UniSwitchElement',
|
||||
'UniTextElement',
|
||||
'UniTextareaElement',
|
||||
'UniViewElement',
|
||||
'UniListViewElement',
|
||||
'UniListItemElement',
|
||||
'UniStickySectionElement',
|
||||
'UniStickyHeaderElement',
|
||||
'UniVideoElement',
|
||||
'UniWebViewElement',
|
||||
'UniMapElement',
|
||||
'UniCoverViewElement',
|
||||
'UniCoverImageElement',
|
||||
'UniPickerElement',
|
||||
],
|
||||
};
|
||||
const uniMiniProgramPreset = {
|
||||
from: 'vue',
|
||||
imports: ['UniElement', 'UniElementImpl'],
|
||||
};
|
||||
const cloudPreset = {
|
||||
'@dcloudio/uni-cloud': ['uniCloud', 'UniCloudError'],
|
||||
};
|
||||
const vuePreset = {
|
||||
from: 'vue',
|
||||
imports: [
|
||||
// vue lifecycle
|
||||
'onActivated',
|
||||
'onBeforeMount',
|
||||
'onBeforeUnmount',
|
||||
'onBeforeUpdate',
|
||||
'onErrorCaptured',
|
||||
'onDeactivated',
|
||||
'onMounted',
|
||||
'onServerPrefetch',
|
||||
'onUnmounted',
|
||||
'onUpdated',
|
||||
// setup helpers
|
||||
'useAttrs',
|
||||
'useSlots',
|
||||
// reactivity,
|
||||
'computed',
|
||||
'customRef',
|
||||
'isReadonly',
|
||||
'isRef',
|
||||
'isProxy',
|
||||
'isReactive',
|
||||
'markRaw',
|
||||
'reactive',
|
||||
'readonly',
|
||||
'ref',
|
||||
'shallowReactive',
|
||||
'shallowReadonly',
|
||||
'shallowRef',
|
||||
'triggerRef',
|
||||
'toRaw',
|
||||
'toRef',
|
||||
'toRefs',
|
||||
'toValue',
|
||||
'unref',
|
||||
'watch',
|
||||
'watchEffect',
|
||||
'watchPostEffect',
|
||||
'watchSyncEffect',
|
||||
// component
|
||||
'defineComponent',
|
||||
'defineAsyncComponent',
|
||||
'getCurrentInstance',
|
||||
'inject',
|
||||
'nextTick',
|
||||
'provide',
|
||||
'useCssModule',
|
||||
'createApp',
|
||||
'hasInjectionContext',
|
||||
// render
|
||||
'h',
|
||||
'mergeProps',
|
||||
'cloneVNode',
|
||||
'isVNode',
|
||||
'resolveComponent',
|
||||
'resolveDirective',
|
||||
'withDirectives',
|
||||
'withModifiers',
|
||||
// effect scope
|
||||
'effectScope',
|
||||
'EffectScope',
|
||||
'getCurrentScope',
|
||||
'onScopeDispose',
|
||||
// types 全部全局导入
|
||||
],
|
||||
};
|
||||
function initAutoImportOptions(platform, { imports = [], ...userOptions }) {
|
||||
rewriteAutoImportOnce();
|
||||
const autoImport = [uniPreset, cloudPreset, vuePreset];
|
||||
if (platform === 'web') {
|
||||
autoImport.push(uniH5Preset);
|
||||
}
|
||||
else if (platform.startsWith('mp-')) {
|
||||
autoImport.push(uniMiniProgramPreset);
|
||||
}
|
||||
return {
|
||||
...userOptions,
|
||||
include: [/\.[u]?ts$/, /\.[u]?vue/],
|
||||
exclude: [/[\\/]\.git[\\/]/],
|
||||
imports: imports.concat(
|
||||
// app-android 平台暂不注入其他
|
||||
platform === 'app-android' ? [] : autoImport),
|
||||
dts: false,
|
||||
};
|
||||
}
|
||||
exports.initAutoImportOptions = initAutoImportOptions;
|
||||
const rewriteAutoImportOnce = (0, uni_shared_1.once)(() => {
|
||||
const unimport = require('unimport');
|
||||
const originalCreateUnimport = unimport.createUnimport;
|
||||
unimport.createUnimport = (opts) => {
|
||||
const unimport_ = originalCreateUnimport(opts);
|
||||
const originalScanImportsFromDir = unimport_.scanImportsFromDir;
|
||||
unimport_.scanImportsFromDir = async (dir, options) => {
|
||||
const exports_ = (await originalScanImportsFromDir(dir, options));
|
||||
scanCustomElements(exports_);
|
||||
return exports_;
|
||||
};
|
||||
return unimport_;
|
||||
};
|
||||
});
|
||||
function scanCustomElements(exports_) {
|
||||
const utsCustomElementsExports = (0, uts_1.getUTSCustomElementsExports)();
|
||||
for (const [key, value] of utsCustomElementsExports.entries()) {
|
||||
value.exports.forEach((export_) => {
|
||||
exports_.push({
|
||||
from: key,
|
||||
name: export_[0],
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { Plugin, ResolveFn } from 'vite';
|
||||
import type { CssUrlReplacer } from './plugins/vitejs/plugins/css';
|
||||
export declare function createEncryptCssUrlReplacer(resolve: ResolveFn): CssUrlReplacer;
|
||||
export declare function uniEncryptUniModulesAssetsPlugin(): Plugin;
|
||||
export declare function uniEncryptUniModulesPlugin(): Plugin;
|
||||
export declare function addUniModulesExtApiComponents(relativeFilename: string, components: string[]): void;
|
||||
export declare function compileCloudUniModuleWithTsc(platform: 'app-android' | 'app-ios' | 'app-harmony', pluginDir: string): Promise<void>;
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.compileCloudUniModuleWithTsc = exports.addUniModulesExtApiComponents = exports.uniEncryptUniModulesPlugin = exports.uniEncryptUniModulesAssetsPlugin = exports.createEncryptCssUrlReplacer = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const uni_modules_cloud_1 = require("../uni_modules.cloud");
|
||||
const utils_1 = require("./plugins/vitejs/utils");
|
||||
const uts_1 = require("../uts");
|
||||
const utils_2 = require("../utils");
|
||||
const easycom_1 = require("../easycom");
|
||||
const uni_modules_1 = require("./plugins/uts/uni_modules");
|
||||
function createEncryptCssUrlReplacer(resolve) {
|
||||
return async (url, importer) => {
|
||||
if (url.startsWith('/') && !url.startsWith('//')) {
|
||||
// /static/logo.png => @/static/logo.png
|
||||
url = '@' + url;
|
||||
}
|
||||
const resolved = await resolve(url, importer);
|
||||
if (resolved) {
|
||||
return ('@/' + (0, utils_2.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, resolved)));
|
||||
}
|
||||
return url;
|
||||
};
|
||||
}
|
||||
exports.createEncryptCssUrlReplacer = createEncryptCssUrlReplacer;
|
||||
// 处理静态资源加载(目前仅限非app-android)
|
||||
function uniEncryptUniModulesAssetsPlugin() {
|
||||
let resolvedConfig;
|
||||
return {
|
||||
name: 'uni:encrypt-uni-modules-assets',
|
||||
enforce: 'pre',
|
||||
configResolved(config) {
|
||||
resolvedConfig = config;
|
||||
},
|
||||
resolveId(id, importer) {
|
||||
if (resolvedConfig.assetsInclude((0, utils_1.cleanUrl)(id))) {
|
||||
id = (0, utils_2.normalizePath)(id);
|
||||
if (importer && (id.startsWith('./') || id.startsWith('../'))) {
|
||||
id = (0, utils_2.normalizePath)(path_1.default.resolve(path_1.default.dirname(importer), id));
|
||||
}
|
||||
if (path_1.default.isAbsolute(id)) {
|
||||
id = '@/' + path_1.default.relative(process.env.UNI_INPUT_DIR, id);
|
||||
}
|
||||
return `\0${id}`;
|
||||
}
|
||||
},
|
||||
load(id) {
|
||||
if (resolvedConfig.assetsInclude((0, utils_1.cleanUrl)(id))) {
|
||||
return {
|
||||
code: `export default ${JSON.stringify(id.replace(/\0/g, ''))}`,
|
||||
moduleSideEffects: false,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniEncryptUniModulesAssetsPlugin = uniEncryptUniModulesAssetsPlugin;
|
||||
function uniEncryptUniModulesPlugin() {
|
||||
let resolvedConfig;
|
||||
return {
|
||||
name: 'uni:encrypt-uni-modules',
|
||||
apply: 'build',
|
||||
config() {
|
||||
return {
|
||||
resolve: {
|
||||
alias: initEncryptUniModulesAlias(),
|
||||
},
|
||||
build: initEncryptUniModulesBuildOptions(process.env.UNI_UTS_PLATFORM, process.env.UNI_INPUT_DIR),
|
||||
};
|
||||
},
|
||||
configResolved(config) {
|
||||
// 编译组件时,禁用内联资源
|
||||
config.build.assetsInlineLimit = 0;
|
||||
config.build.rollupOptions.external = createExternal(config);
|
||||
resolvedConfig = config;
|
||||
},
|
||||
resolveId(id, importer) {
|
||||
if (process.env.UNI_UTS_PLATFORM !== 'app-android') {
|
||||
if (resolvedConfig.assetsInclude((0, utils_1.cleanUrl)(id))) {
|
||||
id = (0, utils_2.normalizePath)(id);
|
||||
if (importer && (id.startsWith('./') || id.startsWith('../'))) {
|
||||
id = (0, utils_2.normalizePath)(path_1.default.resolve(path_1.default.dirname(importer), id));
|
||||
}
|
||||
if (path_1.default.isAbsolute(id)) {
|
||||
id = '@/' + path_1.default.relative(process.env.UNI_INPUT_DIR, id);
|
||||
}
|
||||
return `\0${id}`;
|
||||
}
|
||||
}
|
||||
},
|
||||
load(id) {
|
||||
if (process.env.UNI_UTS_PLATFORM !== 'app-android') {
|
||||
if (resolvedConfig.assetsInclude((0, utils_1.cleanUrl)(id))) {
|
||||
return {
|
||||
code: `export default ${JSON.stringify(id.replace(/\0/g, ''))}`,
|
||||
moduleSideEffects: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
},
|
||||
generateBundle(_, bundle) {
|
||||
Object.keys(bundle).forEach((fileName) => {
|
||||
if (fileName.endsWith('.module.js')) {
|
||||
const uniModuleId = path_1.default.basename(fileName).replace('.module.js', '');
|
||||
// app-android 不需要 js
|
||||
if (process.env.UNI_UTS_PLATFORM !== 'app-android') {
|
||||
const newFileName = 'uni_modules/' +
|
||||
fileName.replace('.module.js', '/index.module.js');
|
||||
bundle[newFileName] = bundle[fileName];
|
||||
bundle[newFileName].fileName = newFileName;
|
||||
}
|
||||
delete bundle[fileName];
|
||||
const pkg = `uni_modules/${uniModuleId}/package.json`;
|
||||
bundle[pkg] = {
|
||||
type: 'asset',
|
||||
fileName: pkg,
|
||||
name: pkg,
|
||||
originalFileName: null,
|
||||
needsCodeReference: false,
|
||||
source: genUniModulesPackageJson(uniModuleId, process.env.UNI_INPUT_DIR, {
|
||||
env: (0, uni_modules_cloud_1.initCheckEnv)(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
});
|
||||
},
|
||||
async writeBundle() {
|
||||
if (process.env.UNI_UTS_PLATFORM !== 'app-android') {
|
||||
return;
|
||||
}
|
||||
const uniXKotlinCompiler = process.env.UNI_APP_X_TSC === 'true'
|
||||
? (0, uts_1.resolveUTSCompiler)().createUniXKotlinCompilerOnce()
|
||||
: null;
|
||||
if (uniXKotlinCompiler) {
|
||||
const tscOutputDir = tscOutDir('app-android');
|
||||
const uniModulesDir = path_1.default.resolve(tscOutputDir, 'uni_modules');
|
||||
if (fs_extra_1.default.existsSync(uniModulesDir)) {
|
||||
for (const plugin of fs_extra_1.default.readdirSync(uniModulesDir)) {
|
||||
const indexFileName = path_1.default.join(uniModulesDir, plugin, 'index.module.uts.ts');
|
||||
if (fs_extra_1.default.existsSync(indexFileName)) {
|
||||
await uniXKotlinCompiler.addRootFile(indexFileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
await uniXKotlinCompiler.close();
|
||||
}
|
||||
// 编译所有 uni_modules 插件
|
||||
const tempOutputDir = uvueOutDir('app-android');
|
||||
const tempUniModulesDir = path_1.default.join(tempOutputDir, 'uni_modules');
|
||||
const tempUniModules = [];
|
||||
if (fs_extra_1.default.existsSync(tempUniModulesDir)) {
|
||||
fs_extra_1.default.readdirSync(tempUniModulesDir).forEach((uniModuleDir) => {
|
||||
if (fs_extra_1.default.existsSync(path_1.default.join(tempUniModulesDir, uniModuleDir, 'index.module.uts'))) {
|
||||
tempUniModules.push(uniModuleDir);
|
||||
}
|
||||
});
|
||||
}
|
||||
const compiler = (0, uts_1.resolveUTSCompiler)();
|
||||
for (const uniModule of tempUniModules) {
|
||||
const pluginDir = path_1.default.resolve(tempUniModulesDir, uniModule);
|
||||
// TODO 待优化autoImports,目前 uni-app x 的编译,autoImport 是在js层处理过,rust层基本不再使用
|
||||
// 但uts插件目前还是使用的rust层的autoImports
|
||||
const autoImports = {};
|
||||
const allAutoImports = (0, easycom_1.getUTSEasyComAutoImports)();
|
||||
Object.keys(allAutoImports).forEach((source) => {
|
||||
if (!source.startsWith(`@/uni_modules/${uniModule}/components/`)) {
|
||||
autoImports[source] = allAutoImports[source];
|
||||
}
|
||||
});
|
||||
const uni_modules = [];
|
||||
const pkgJson = path_1.default.resolve(process.env.UNI_INPUT_DIR, 'uni_modules', uniModule, 'package.json');
|
||||
if (fs_extra_1.default.existsSync(pkgJson)) {
|
||||
try {
|
||||
const pkg = require(pkgJson);
|
||||
if (pkg.uni_modules?.dependencies) {
|
||||
uni_modules.push(...pkg.uni_modules.dependencies);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
const result = await compiler.compile(pluginDir, {
|
||||
isX: process.env.UNI_APP_X === 'true',
|
||||
isSingleThread: true,
|
||||
isPlugin: false,
|
||||
sourceMap: false,
|
||||
uni_modules,
|
||||
transform: {
|
||||
uvueClassNamePrefix: 'Gen',
|
||||
autoImports,
|
||||
uvueGenDefaultAs: '__sfc__',
|
||||
},
|
||||
});
|
||||
if (result) {
|
||||
const apis = result.inject_apis;
|
||||
const scopedSlots = result.scoped_slots;
|
||||
const customElements = result.custom_elements;
|
||||
const components = getUniModulesExtApiComponents(uniModule);
|
||||
const modules = (0, uts_1.resolveUTSCompiler)().parseInjectModules(apis, {}, components);
|
||||
fs_extra_1.default.writeFileSync(path_1.default.resolve(process.env.UNI_OUTPUT_DIR, 'uni_modules', uniModule, 'package.json'), genUniModulesPackageJson(uniModule, process.env.UNI_INPUT_DIR, {
|
||||
env: (0, uni_modules_cloud_1.initCheckEnv)(),
|
||||
apis,
|
||||
components,
|
||||
modules,
|
||||
scopedSlots,
|
||||
customElements,
|
||||
}));
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniEncryptUniModulesPlugin = uniEncryptUniModulesPlugin;
|
||||
function tscOutDir(platform) {
|
||||
return path_1.default.join(process.env.UNI_APP_X_TSC_DIR, platform);
|
||||
}
|
||||
function uvueOutDir(platform) {
|
||||
return path_1.default.join(process.env.UNI_APP_X_UVUE_DIR, platform);
|
||||
}
|
||||
function createExternal(config) {
|
||||
return function external(source) {
|
||||
if ([
|
||||
'vue',
|
||||
'plugin-vue:export-helper',
|
||||
'vue-router',
|
||||
'pinia',
|
||||
'vuex',
|
||||
'vue-i18n',
|
||||
].includes(source)) {
|
||||
return true;
|
||||
}
|
||||
if (source.startsWith('@vue/')) {
|
||||
return true;
|
||||
}
|
||||
if (source.startsWith('@dcloudio/')) {
|
||||
return true;
|
||||
}
|
||||
if (source.startsWith('@/uni_modules/')) {
|
||||
return true;
|
||||
}
|
||||
// 相对目录
|
||||
if (source.startsWith('@/') || source.startsWith('.')) {
|
||||
return false;
|
||||
}
|
||||
if (path_1.default.isAbsolute(source)) {
|
||||
return false;
|
||||
}
|
||||
// 'virtual:uno.css'
|
||||
if (source.includes(':')) {
|
||||
return false;
|
||||
}
|
||||
// android 系统库,三方库,iOS 的库呢?一般不包含.
|
||||
if (source.includes('.')) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
function initEncryptUniModulesAlias() {
|
||||
return [
|
||||
{
|
||||
find: '\0plugin-vue:export-helper',
|
||||
replacement: 'plugin-vue:export-helper',
|
||||
},
|
||||
];
|
||||
}
|
||||
function initEncryptUniModulesBuildOptions(platform, inputDir) {
|
||||
const modules = (0, uni_modules_cloud_1.parseUniModulesWithComponents)(inputDir, platform);
|
||||
const moduleNames = Object.keys(modules);
|
||||
if (!moduleNames.length) {
|
||||
throw new Error('No encrypt uni_modules found');
|
||||
}
|
||||
// 生成入口文件
|
||||
const input = {};
|
||||
moduleNames.forEach((module) => {
|
||||
const moduleDir = path_1.default.resolve(inputDir, 'uni_modules', module);
|
||||
const indexEncryptFile = path_1.default.resolve(moduleDir, 'index.module.uts');
|
||||
if (modules[module]) {
|
||||
fs_extra_1.default.writeFileSync(indexEncryptFile, modules[module]);
|
||||
// 输出 xxx.module ,确保相对路径的准确性,因为真正引用的时候,是从 @/uni_modules/xxx 引入的
|
||||
input[module + '.module'] = indexEncryptFile;
|
||||
}
|
||||
});
|
||||
return {
|
||||
lib: false, // 不使用 lib 模式,lib模式会直接内联资源
|
||||
cssCodeSplit: false,
|
||||
// outDir: process.env.UNI_OUTPUT_DIR,
|
||||
rollupOptions: {
|
||||
preserveEntrySignatures: 'strict',
|
||||
input,
|
||||
output: {
|
||||
format: 'es',
|
||||
banner: ``,
|
||||
entryFileNames: '[name].js',
|
||||
assetFileNames(asset) {
|
||||
if (asset.name && path_1.default.isAbsolute(asset.name)) {
|
||||
const uniModuleId = parseUniModuleId(path_1.default.relative(inputDir, asset.name));
|
||||
if (uniModuleId) {
|
||||
return `uni_modules/${uniModuleId}/assets/[name]-[hash][extname]`;
|
||||
}
|
||||
}
|
||||
return 'assets/[name]-[hash][extname]';
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
function genUniModulesPackageJson(uniModuleId, inputDir, artifacts) {
|
||||
const pkg = require(path_1.default.resolve(inputDir, path_1.default.join('uni_modules', uniModuleId, 'package.json')));
|
||||
return JSON.stringify({
|
||||
id: pkg.id,
|
||||
version: pkg.version,
|
||||
uni_modules: {
|
||||
dependencies: pkg.uni_modules?.dependencies || [],
|
||||
artifacts,
|
||||
},
|
||||
}, null, 2);
|
||||
}
|
||||
function parseUniModuleId(relativeFilename) {
|
||||
const parts = (0, utils_2.normalizePath)(relativeFilename).split('/', 2);
|
||||
if (parts[0] === 'uni_modules') {
|
||||
return parts[1];
|
||||
}
|
||||
}
|
||||
const uniModulesExtApiComponents = new Map();
|
||||
function addUniModulesExtApiComponents(relativeFilename, components) {
|
||||
const uniModuleId = parseUniModuleId(relativeFilename);
|
||||
if (uniModuleId) {
|
||||
let extApiComponents = uniModulesExtApiComponents.get(uniModuleId);
|
||||
if (!extApiComponents) {
|
||||
extApiComponents = new Set();
|
||||
uniModulesExtApiComponents.set(uniModuleId, extApiComponents);
|
||||
}
|
||||
components.forEach((component) => extApiComponents.add(component));
|
||||
}
|
||||
}
|
||||
exports.addUniModulesExtApiComponents = addUniModulesExtApiComponents;
|
||||
function getUniModulesExtApiComponents(uniModuleId) {
|
||||
return [...(uniModulesExtApiComponents.get(uniModuleId) || [])];
|
||||
}
|
||||
function compileCloudUniModuleWithTsc(platform, pluginDir) {
|
||||
const { compileUniModuleWithTsc, createUniXKotlinCompilerOnce, createUniXSwiftCompilerOnce, createUniXArkTSCompilerOnce, } = (0, uts_1.resolveUTSCompiler)();
|
||||
const isX = process.env.UNI_APP_X === 'true';
|
||||
return compileUniModuleWithTsc(platform, pluginDir, platform === 'app-android'
|
||||
? createUniXKotlinCompilerOnce()
|
||||
: platform === 'app-harmony'
|
||||
? createUniXArkTSCompilerOnce()
|
||||
: createUniXSwiftCompilerOnce(), {
|
||||
rootFiles: [],
|
||||
preprocessor: platform === 'app-android'
|
||||
? (0, uni_modules_1.createAppAndroidUniModulesSyncFilePreprocessorOnce)(isX)
|
||||
: platform === 'app-harmony'
|
||||
? (0, uni_modules_1.createAppHarmonyUniModulesSyncFilePreprocessorOnce)(isX)
|
||||
: (0, uni_modules_1.createAppIosUniModulesSyncFilePreprocessorOnce)(isX),
|
||||
});
|
||||
}
|
||||
exports.compileCloudUniModuleWithTsc = compileCloudUniModuleWithTsc;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniUniModulesExtApiPlugin(): Plugin;
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniUniModulesExtApiPlugin = void 0;
|
||||
const uts_1 = require("../uts");
|
||||
const resolve_1 = require("../resolve");
|
||||
function uniUniModulesExtApiPlugin() {
|
||||
return {
|
||||
name: 'uni:uni-modules_ext-api',
|
||||
apply: 'build',
|
||||
config() {
|
||||
const rollupOptions = {
|
||||
input: (0, resolve_1.resolveMainPathOnce)(process.env.UNI_INPUT_DIR),
|
||||
external: ['vue'],
|
||||
output: {
|
||||
format: 'iife',
|
||||
entryFileNames: 'components.js',
|
||||
globals: {
|
||||
vue: 'Vue',
|
||||
uni: 'uni',
|
||||
},
|
||||
},
|
||||
};
|
||||
const build = {};
|
||||
if (['app-ios', 'app-harmony'].includes(process.env.UNI_UTS_PLATFORM)) {
|
||||
build.rollupOptions = rollupOptions;
|
||||
}
|
||||
return {
|
||||
build,
|
||||
};
|
||||
},
|
||||
load(id) {
|
||||
if ((0, uts_1.isUTSProxy)(id)) {
|
||||
return '';
|
||||
}
|
||||
},
|
||||
// generateBundle(_, bundle) {
|
||||
// Object.keys(bundle).forEach((fileName) => {
|
||||
// console.log('fileName', fileName)
|
||||
// })
|
||||
// },
|
||||
};
|
||||
}
|
||||
exports.uniUniModulesExtApiPlugin = uniUniModulesExtApiPlugin;
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import type { ConfigEnv } from 'vite';
|
||||
export type FEATURE_DEFINES = ReturnType<typeof initFeatures>;
|
||||
interface InitFeaturesOptions {
|
||||
pagesJson: UniApp.PagesJson;
|
||||
manifestJson: any;
|
||||
inputDir: string;
|
||||
platform: UniApp.PLATFORM;
|
||||
command: ConfigEnv['command'];
|
||||
ssr: boolean;
|
||||
}
|
||||
export declare function initFeatures(options: InitFeaturesOptions): {
|
||||
__VUE_OPTIONS_API__: boolean;
|
||||
__VUE_PROD_DEVTOOLS__: boolean;
|
||||
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: boolean;
|
||||
__UNI_FEATURE_WX__: boolean;
|
||||
__UNI_FEATURE_WXS__: boolean;
|
||||
__UNI_FEATURE_RPX__: boolean;
|
||||
__UNI_FEATURE_PROMISE__: boolean;
|
||||
__UNI_FEATURE_LONGPRESS__: boolean;
|
||||
__UNI_FEATURE_I18N_EN__: boolean;
|
||||
__UNI_FEATURE_I18N_ES__: boolean;
|
||||
__UNI_FEATURE_I18N_FR__: boolean;
|
||||
__UNI_FEATURE_I18N_ZH_HANS__: boolean;
|
||||
__UNI_FEATURE_I18N_ZH_HANT__: boolean;
|
||||
__UNI_FEATURE_UNI_CLOUD__: boolean;
|
||||
__UNI_FEATURE_I18N_LOCALE__: boolean;
|
||||
__UNI_FEATURE_NVUE__: boolean;
|
||||
__UNI_FEATURE_ROUTER_MODE__: "\"hash\"" | "\"history\"";
|
||||
__UNI_FEATURE_PAGES__: boolean;
|
||||
__UNI_FEATURE_TABBAR__: boolean;
|
||||
__UNI_FEATURE_TABBAR_MIDBUTTON__: boolean;
|
||||
__UNI_FEATURE_TOPWINDOW__: boolean;
|
||||
__UNI_FEATURE_LEFTWINDOW__: boolean;
|
||||
__UNI_FEATURE_RIGHTWINDOW__: boolean;
|
||||
__UNI_FEATURE_RESPONSIVE__: boolean;
|
||||
__UNI_FEATURE_NAVIGATIONBAR__: boolean;
|
||||
__UNI_FEATURE_PULL_DOWN_REFRESH__: boolean;
|
||||
__UNI_FEATURE_NAVIGATIONBAR_BUTTONS__: boolean;
|
||||
__UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__: boolean;
|
||||
__UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__: boolean;
|
||||
};
|
||||
export {};
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initFeatures = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
function initProjectFeature({ inputDir }) {
|
||||
const features = {
|
||||
i18nLocale: false,
|
||||
i18nEn: true,
|
||||
i18nEs: true,
|
||||
i18nFr: true,
|
||||
i18nZhHans: true,
|
||||
i18nZhHant: true,
|
||||
uniCloud: false,
|
||||
};
|
||||
const localesDir = path_1.default.resolve(inputDir, 'locale');
|
||||
if (fs_1.default.existsSync(localesDir)) {
|
||||
if (fs_1.default.readdirSync(localesDir).find((file) => path_1.default.extname(file) === '.json')) {
|
||||
features.i18nLocale = true;
|
||||
}
|
||||
}
|
||||
if (process.env.UNI_CLOUD_PROVIDER) {
|
||||
try {
|
||||
const providers = JSON.parse(process.env.UNI_CLOUD_PROVIDER);
|
||||
if (providers.length) {
|
||||
features.uniCloud = true;
|
||||
}
|
||||
}
|
||||
catch (e) { }
|
||||
}
|
||||
return features;
|
||||
}
|
||||
function initPagesFeature({ pagesJson, command, inputDir, ssr, }) {
|
||||
const features = {
|
||||
nvue: true,
|
||||
pages: true,
|
||||
tabBar: true,
|
||||
tabBarMidButton: true,
|
||||
topWindow: false,
|
||||
leftWindow: false,
|
||||
rightWindow: false,
|
||||
navigationBar: true,
|
||||
pullDownRefresh: false,
|
||||
navigationBarButtons: true,
|
||||
navigationBarSearchInput: true,
|
||||
navigationBarTransparent: true,
|
||||
};
|
||||
const { tabBar, pages, topWindow, leftWindow, rightWindow, globalStyle } = pagesJson;
|
||||
// ssr 时强制启用多页面(需要用到router)
|
||||
if (!ssr && pages && pages.length === 1) {
|
||||
features.pages = false;
|
||||
}
|
||||
if (!(tabBar && tabBar.list && tabBar.list.length)) {
|
||||
features.tabBar = false;
|
||||
features.tabBarMidButton = false;
|
||||
}
|
||||
if (features.tabBar && !tabBar.midButton) {
|
||||
features.tabBarMidButton = false;
|
||||
}
|
||||
if (topWindow && topWindow.path) {
|
||||
features.topWindow = true;
|
||||
}
|
||||
if (leftWindow && leftWindow.path) {
|
||||
features.leftWindow = true;
|
||||
}
|
||||
if (rightWindow && rightWindow.path) {
|
||||
features.rightWindow = true;
|
||||
}
|
||||
if (globalStyle.enablePullDownRefresh) {
|
||||
features.pullDownRefresh = true;
|
||||
}
|
||||
else {
|
||||
if (pages.find((page) => page.style && page.style.enablePullDownRefresh)) {
|
||||
features.pullDownRefresh = true;
|
||||
}
|
||||
}
|
||||
if (command === 'build') {
|
||||
if (!pages.find((page) => fs_1.default.existsSync(path_1.default.resolve(inputDir, page.path + '.nvue')))) {
|
||||
features.nvue = false;
|
||||
}
|
||||
let isNavigationCustom = false;
|
||||
if (globalStyle.navigationBar.style === 'custom') {
|
||||
isNavigationCustom = true; // 全局custom
|
||||
if (pages.find((page) => page.style.navigationBar.style === 'default')) {
|
||||
isNavigationCustom = false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// 所有页面均custom
|
||||
if (pages.every((page) => page.style.navigationBar.style === 'custom')) {
|
||||
isNavigationCustom = true;
|
||||
}
|
||||
}
|
||||
if (isNavigationCustom) {
|
||||
features.navigationBar = false;
|
||||
features.navigationBarButtons = false;
|
||||
features.navigationBarSearchInput = false;
|
||||
features.navigationBarTransparent = false;
|
||||
}
|
||||
else {
|
||||
if (!pages.find((page) => (0, shared_1.isArray)(page.style.navigationBar.buttons) &&
|
||||
page.style.navigationBar.buttons.length)) {
|
||||
features.navigationBarButtons = false;
|
||||
}
|
||||
if (!globalStyle.navigationBar.searchInput &&
|
||||
!pages.find((page) => page.style.navigationBar.searchInput)) {
|
||||
features.navigationBarSearchInput = false;
|
||||
}
|
||||
if (globalStyle.navigationBar.type !== 'transparent' &&
|
||||
!pages.find((page) => page.style.navigationBar.type === 'transparent')) {
|
||||
features.navigationBarTransparent = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return features;
|
||||
}
|
||||
function initManifestFeature({ manifestJson, command, platform, }) {
|
||||
const features = {
|
||||
wx: false,
|
||||
wxs: true,
|
||||
rpx: true,
|
||||
promise: false,
|
||||
longpress: true,
|
||||
routerMode: '"hash"',
|
||||
vueOptionsApi: true,
|
||||
vueProdDevTools: false,
|
||||
vueProdHydrationMismatchDetails: false,
|
||||
};
|
||||
if (command === 'build') {
|
||||
// TODO 需要预编译一遍?
|
||||
// features.wxs = false
|
||||
// features.longpress = false
|
||||
}
|
||||
const webManifest = manifestJson.web || manifestJson.h5;
|
||||
if (webManifest &&
|
||||
webManifest.router &&
|
||||
webManifest.router.mode === 'history') {
|
||||
features.routerMode = '"history"';
|
||||
}
|
||||
// TODO other features
|
||||
return features;
|
||||
}
|
||||
function initFeatures(options) {
|
||||
const { wx, wxs, rpx, nvue, uniCloud, i18nEn, i18nEs, i18nFr, i18nZhHans, i18nZhHant, i18nLocale, vueOptionsApi, vueProdDevTools, vueProdHydrationMismatchDetails, pages, tabBar, tabBarMidButton, promise, longpress, routerMode, topWindow, leftWindow, rightWindow, navigationBar, pullDownRefresh, navigationBarButtons, navigationBarSearchInput, navigationBarTransparent, } = (0, shared_1.extend)(initManifestFeature(options), initPagesFeature(options), initProjectFeature(options));
|
||||
// uni-app-x运行时可调用$setPageStyle,需启用相关特性方可支持。否则$setPageStyle无效果
|
||||
const features = {
|
||||
// vue
|
||||
__VUE_OPTIONS_API__: vueOptionsApi, // enable/disable Options API support, default: true
|
||||
__VUE_PROD_DEVTOOLS__: vueProdDevTools, // enable/disable devtools support in production, default: false
|
||||
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: vueProdHydrationMismatchDetails,
|
||||
// uni
|
||||
__UNI_FEATURE_WX__: wx, // 是否启用小程序的组件实例 API,如:selectComponent 等(uni-core/src/service/plugin/appConfig)
|
||||
__UNI_FEATURE_WXS__: wxs, // 是否启用 wxs 支持,如:getComponentDescriptor 等(uni-core/src/view/plugin/appConfig)
|
||||
__UNI_FEATURE_RPX__: rpx, // 是否启用运行时 rpx 支持
|
||||
__UNI_FEATURE_PROMISE__: promise, // 是否启用旧版本的 promise 支持(即返回[err,res]的格式),默认返回标准
|
||||
__UNI_FEATURE_LONGPRESS__: longpress, // 是否启用longpress
|
||||
__UNI_FEATURE_I18N_EN__: i18nEn, // 是否启用en
|
||||
__UNI_FEATURE_I18N_ES__: i18nEs, // 是否启用es
|
||||
__UNI_FEATURE_I18N_FR__: i18nFr, // 是否启用fr
|
||||
__UNI_FEATURE_I18N_ZH_HANS__: i18nZhHans, // 是否启用zh_Hans
|
||||
__UNI_FEATURE_I18N_ZH_HANT__: i18nZhHant, // 是否启用zh_Hant
|
||||
// 以下特性,编译器已自动识别是否需要启用
|
||||
__UNI_FEATURE_UNI_CLOUD__: uniCloud, // 是否启用uniCloud
|
||||
__UNI_FEATURE_I18N_LOCALE__: i18nLocale, // 是否启用i18n
|
||||
__UNI_FEATURE_NVUE__: nvue, // 是否启用nvue
|
||||
__UNI_FEATURE_ROUTER_MODE__: routerMode, // 路由模式
|
||||
__UNI_FEATURE_PAGES__: pages, // 是否多页面
|
||||
__UNI_FEATURE_TABBAR__: tabBar, // 是否包含tabBar
|
||||
__UNI_FEATURE_TABBAR_MIDBUTTON__: tabBarMidButton, // 是否包含midButton
|
||||
__UNI_FEATURE_TOPWINDOW__: topWindow, // 是否包含topWindow
|
||||
__UNI_FEATURE_LEFTWINDOW__: leftWindow, // 是否包含leftWindow
|
||||
__UNI_FEATURE_RIGHTWINDOW__: rightWindow, // 是否包含rightWindow
|
||||
__UNI_FEATURE_RESPONSIVE__: topWindow || leftWindow || rightWindow, // 是否启用响应式
|
||||
__UNI_FEATURE_NAVIGATIONBAR__: navigationBar, // 是否启用标题栏
|
||||
__UNI_FEATURE_PULL_DOWN_REFRESH__: pullDownRefresh, // 是否启用下拉刷新
|
||||
__UNI_FEATURE_NAVIGATIONBAR_BUTTONS__: navigationBarButtons, // 是否启用标题栏按钮
|
||||
__UNI_FEATURE_NAVIGATIONBAR_SEARCHINPUT__: navigationBarSearchInput, // 是否启用标题栏搜索框
|
||||
__UNI_FEATURE_NAVIGATIONBAR_TRANSPARENT__: navigationBarTransparent, // 是否启用透明标题栏
|
||||
};
|
||||
// ssr nodejs features
|
||||
if (options.ssr) {
|
||||
Object.keys(features).forEach((name) => {
|
||||
const value = features[name];
|
||||
(0, shared_1.extend)(globalThis, {
|
||||
[name]: (0, shared_1.isString)(value) ? JSON.parse(value) : value,
|
||||
});
|
||||
});
|
||||
}
|
||||
return features;
|
||||
}
|
||||
exports.initFeatures = initFeatures;
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { EmittedAsset } from 'rollup';
|
||||
import type { ParserOptions } from '@vue/compiler-core';
|
||||
import type { CompilerOptions, SFCStyleCompileOptions, TemplateCompiler } from '@vue/compiler-sfc';
|
||||
import type { UniViteCopyPluginOptions } from './plugins/copy';
|
||||
export { getIsStaticFile } from './plugins/vitejs/plugins/static';
|
||||
export declare const cssTarget = "chrome53";
|
||||
export interface CopyOptions {
|
||||
/**
|
||||
* 静态资源,配置的目录,在 uni_modules 中同样支持
|
||||
*/
|
||||
assets?: string[];
|
||||
targets?: UniViteCopyPluginOptions['targets'];
|
||||
}
|
||||
interface UniVitePluginUniOptions {
|
||||
compiler?: TemplateCompiler;
|
||||
styleOptions?: Pick<SFCStyleCompileOptions, 'postcssPlugins'>;
|
||||
compilerOptions?: {
|
||||
miniProgram?: {
|
||||
emitFile?: (emittedFile: EmittedAsset) => string;
|
||||
};
|
||||
isNativeTag?: ParserOptions['isNativeTag'];
|
||||
isVoidTag?: ParserOptions['isVoidTag'];
|
||||
isCustomElement?: ParserOptions['isCustomElement'];
|
||||
directiveTransforms?: CompilerOptions['directiveTransforms'];
|
||||
nodeTransforms?: CompilerOptions['nodeTransforms'];
|
||||
whitespace?: CompilerOptions['whitespace'];
|
||||
};
|
||||
jsxOptions?: {
|
||||
babelPlugins?: any[];
|
||||
};
|
||||
copyOptions?: CopyOptions | (() => CopyOptions);
|
||||
}
|
||||
export interface UniVitePlugin extends Plugin {
|
||||
uni?: UniVitePluginUniOptions;
|
||||
}
|
||||
export * from './utils';
|
||||
export * from './plugins';
|
||||
export * from './features';
|
||||
export * from './autoImport';
|
||||
export * from './cloud';
|
||||
export * from './extApi';
|
||||
export declare function rewriteExistsSyncHasRootFile(): void;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.rewriteExistsSyncHasRootFile = exports.cssTarget = exports.getIsStaticFile = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
var static_1 = require("./plugins/vitejs/plugins/static");
|
||||
Object.defineProperty(exports, "getIsStaticFile", { enumerable: true, get: function () { return static_1.getIsStaticFile; } });
|
||||
exports.cssTarget = 'chrome53';
|
||||
__exportStar(require("./utils"), exports);
|
||||
__exportStar(require("./plugins"), exports);
|
||||
__exportStar(require("./features"), exports);
|
||||
__exportStar(require("./autoImport"), exports);
|
||||
__exportStar(require("./cloud"), exports);
|
||||
__exportStar(require("./extApi"), exports);
|
||||
// https://github.com/vitejs/vite/blob/aac2ef77521f66ddd908f9d97020b8df532148cf/packages/vite/src/node/server/searchRoot.ts#L38
|
||||
// vite 在初始化阶段会执行 initTSConfck,此时会 searchForWorkspaceRoot,如果找到了 pnpm-workspace.yaml 文件,会将其作为 root
|
||||
// HBuilderX 项目,root 一定是 UNI_INPUT_DIR,所以需要重写 fs.existsSync,不重写的话,可能会找错,
|
||||
// 一旦找错目录,而该目录下有 N 多文件目录,会导致遍历及其缓慢
|
||||
function rewriteExistsSyncHasRootFile() {
|
||||
const existsSync = fs_1.default.existsSync;
|
||||
const pnpmWorkspaceYaml = path_1.default.join(process.env.UNI_INPUT_DIR, 'pnpm-workspace.yaml');
|
||||
fs_1.default.existsSync = (path) => {
|
||||
if (path === pnpmWorkspaceYaml) {
|
||||
return true;
|
||||
}
|
||||
return existsSync(path);
|
||||
};
|
||||
}
|
||||
exports.rewriteExistsSyncHasRootFile = rewriteExistsSyncHasRootFile;
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import { type FilterPattern } from '@rollup/pluginutils';
|
||||
export interface ConsoleOptions {
|
||||
method: string;
|
||||
filename?: (filename: string) => string;
|
||||
include?: FilterPattern;
|
||||
exclude?: FilterPattern;
|
||||
}
|
||||
export declare function uniConsolePlugin(options: ConsoleOptions): Plugin;
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniConsolePlugin = void 0;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const pluginutils_1 = require("@rollup/pluginutils");
|
||||
const utils_1 = require("../utils");
|
||||
const console_1 = require("../../logs/console");
|
||||
const utils_2 = require("../../vite/utils/utils");
|
||||
const filter_1 = require("../../filter");
|
||||
const debugConsole = (0, debug_1.default)('uni:console');
|
||||
function uniConsolePlugin(options) {
|
||||
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
|
||||
let resolvedConfig;
|
||||
return {
|
||||
name: 'uni:console',
|
||||
enforce: 'pre',
|
||||
configResolved(config) {
|
||||
resolvedConfig = config;
|
||||
},
|
||||
transform(code, id) {
|
||||
if ((0, filter_1.isRenderjs)(id) || (0, filter_1.isWxs)(id)) {
|
||||
return {
|
||||
code: (0, console_1.restoreConsoleExpr)(code),
|
||||
map: { mappings: '' },
|
||||
};
|
||||
}
|
||||
if (!filter(id))
|
||||
return null;
|
||||
if (!(0, utils_1.isJsFile)(id))
|
||||
return null;
|
||||
let { filename } = (0, utils_1.parseVueRequest)(id);
|
||||
if (options.filename) {
|
||||
filename = options.filename(filename);
|
||||
}
|
||||
if (!filename) {
|
||||
return null;
|
||||
}
|
||||
if (!code.includes('console.')) {
|
||||
return null;
|
||||
}
|
||||
debugConsole(id);
|
||||
return (0, console_1.rewriteConsoleExpr)(options.method, id, filename, code, (0, utils_2.withSourcemap)(resolvedConfig));
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniConsolePlugin = uniConsolePlugin;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import type { WatchOptions } from 'chokidar';
|
||||
import type { Plugin } from 'vite';
|
||||
import { type FileWatcherOptions } from '../../watcher';
|
||||
export type UniViteCopyPluginTarget = Omit<FileWatcherOptions, 'verbose'> & {
|
||||
watchOptions?: WatchOptions & {
|
||||
readyTimeout?: number;
|
||||
};
|
||||
};
|
||||
export interface UniViteCopyPluginOptions {
|
||||
targets: UniViteCopyPluginTarget[];
|
||||
}
|
||||
export declare function uniViteCopyPlugin({ targets, }: UniViteCopyPluginOptions): Plugin;
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniViteCopyPlugin = void 0;
|
||||
const watcher_1 = require("../../watcher");
|
||||
const messages_1 = require("../../messages");
|
||||
const logs_1 = require("../../logs");
|
||||
const uni_shared_1 = require("@dcloudio/uni-shared");
|
||||
function uniViteCopyPlugin({ targets, }) {
|
||||
let resolvedConfig;
|
||||
let initialized = false;
|
||||
let isFirstBuild = true;
|
||||
return {
|
||||
name: 'uni:copy',
|
||||
apply: 'build',
|
||||
configResolved(config) {
|
||||
resolvedConfig = config;
|
||||
},
|
||||
async writeBundle() {
|
||||
if (initialized) {
|
||||
return;
|
||||
}
|
||||
if (resolvedConfig.build.ssr) {
|
||||
return;
|
||||
}
|
||||
initialized = true;
|
||||
const is_prod = process.env.NODE_ENV !== 'development' ||
|
||||
process.env.UNI_AUTOMATOR_CONFIG;
|
||||
const onChange = is_prod
|
||||
? undefined
|
||||
: (0, uni_shared_1.debounce)(() => {
|
||||
if (isFirstBuild) {
|
||||
return;
|
||||
}
|
||||
(0, logs_1.resetOutput)('log');
|
||||
(0, logs_1.output)('log', messages_1.M['dev.watching.end']);
|
||||
}, 100, { setTimeout, clearTimeout });
|
||||
return new Promise((resolve) => {
|
||||
Promise.all(targets.map(({ watchOptions, ...target }) => {
|
||||
return new Promise((resolve) => {
|
||||
new watcher_1.FileWatcher({
|
||||
...target,
|
||||
}).watch({
|
||||
cwd: process.env.UNI_INPUT_DIR,
|
||||
persistent: is_prod ? false : true,
|
||||
...watchOptions,
|
||||
}, () => {
|
||||
resolve(void 0);
|
||||
}, onChange);
|
||||
});
|
||||
})).then(() => resolve());
|
||||
});
|
||||
},
|
||||
closeBundle() {
|
||||
isFirstBuild = false;
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniViteCopyPlugin = uniViteCopyPlugin;
|
||||
Generated
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function addScoped(code: string): string;
|
||||
interface UniCssScopedPluginOptions {
|
||||
filter: (id: string) => boolean;
|
||||
}
|
||||
export declare function uniRemoveCssScopedPlugin(_?: UniCssScopedPluginOptions): Plugin;
|
||||
export declare function uniCssScopedPlugin({ filter }?: UniCssScopedPluginOptions): Plugin;
|
||||
export {};
|
||||
Generated
Vendored
+83
@@ -0,0 +1,83 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniCssScopedPlugin = exports.uniRemoveCssScopedPlugin = exports.addScoped = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const constants_1 = require("../../constants");
|
||||
const preprocess_1 = require("../../preprocess");
|
||||
const parse_1 = require("../../vue/parse");
|
||||
const utils_1 = require("../../utils");
|
||||
const utils_2 = require("../../vue/utils");
|
||||
const debugScoped = (0, debug_1.default)('uni:scoped');
|
||||
const SCOPED_RE = /<style\s[^>]*scoped[^>]*>/i;
|
||||
function addScoped(code) {
|
||||
return code.replace(/(<style\b[^><]*)>/gi, (str, $1) => {
|
||||
if ($1.includes('scoped')) {
|
||||
return str;
|
||||
}
|
||||
return `${$1} scoped>`;
|
||||
});
|
||||
}
|
||||
exports.addScoped = addScoped;
|
||||
function removeScoped(code) {
|
||||
if (!SCOPED_RE.test(code)) {
|
||||
return code;
|
||||
}
|
||||
return code.replace(/(<style.*)scoped(.*>)/gi, '$1$2');
|
||||
}
|
||||
function uniRemoveCssScopedPlugin(_ = { filter: () => false }) {
|
||||
return {
|
||||
name: 'uni:css-remove-scoped',
|
||||
enforce: 'pre',
|
||||
transform(code, id) {
|
||||
if (!(0, utils_2.isVueSfcFile)(id))
|
||||
return null;
|
||||
debugScoped(id);
|
||||
return {
|
||||
code: removeScoped(code),
|
||||
map: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniRemoveCssScopedPlugin = uniRemoveCssScopedPlugin;
|
||||
function uniCssScopedPlugin({ filter } = { filter: () => false }) {
|
||||
return {
|
||||
name: 'uni:css-scoped',
|
||||
enforce: 'pre',
|
||||
transform(code, id) {
|
||||
if (!filter(id))
|
||||
return null;
|
||||
debugScoped(id);
|
||||
return {
|
||||
code: addScoped(code),
|
||||
map: null,
|
||||
};
|
||||
},
|
||||
// 仅 h5
|
||||
handleHotUpdate(ctx) {
|
||||
if (!constants_1.EXTNAME_VUE.includes(path_1.default.extname(ctx.file))) {
|
||||
return;
|
||||
}
|
||||
const scoped = !(0, utils_1.isAppVue)(ctx.file);
|
||||
debugScoped('hmr', ctx.file);
|
||||
const oldRead = ctx.read;
|
||||
ctx.read = async () => {
|
||||
let code = await oldRead();
|
||||
// hotUpdate preprocess
|
||||
if (code.includes('#endif')) {
|
||||
code = (0, preprocess_1.preJs)((0, preprocess_1.preHtml)(code, ctx.file), ctx.file);
|
||||
}
|
||||
if (scoped) {
|
||||
code = addScoped(code);
|
||||
}
|
||||
// 处理 block, wxs 等
|
||||
return (0, parse_1.parseVueCode)(code).code;
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniCssScopedPlugin = uniCssScopedPlugin;
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function dynamicImportPolyfill(promise?: boolean): Plugin;
|
||||
Generated
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.dynamicImportPolyfill = void 0;
|
||||
function dynamicImportPolyfill(promise = false) {
|
||||
return {
|
||||
name: 'dynamic-import-polyfill',
|
||||
renderDynamicImport() {
|
||||
return {
|
||||
left: promise ? 'Promise.resolve(' : '(',
|
||||
right: ')',
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.dynamicImportPolyfill = dynamicImportPolyfill;
|
||||
Generated
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import { type FilterPattern } from '@rollup/pluginutils';
|
||||
interface UniEasycomPluginOptions {
|
||||
include?: FilterPattern;
|
||||
exclude?: FilterPattern;
|
||||
}
|
||||
export declare function uniEasycomPlugin(options: UniEasycomPluginOptions): Plugin;
|
||||
export {};
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniEasycomPlugin = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
const pluginutils_1 = require("@rollup/pluginutils");
|
||||
const url_1 = require("../utils/url");
|
||||
const constants_1 = require("../../constants");
|
||||
const easycom_1 = require("../../easycom");
|
||||
const transformUTSComponent_1 = require("../../vue/transforms/transformUTSComponent");
|
||||
const uts_1 = require("../../uts");
|
||||
function uniEasycomPlugin(options) {
|
||||
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
|
||||
return {
|
||||
name: 'uni:app-easycom',
|
||||
transform(code, id) {
|
||||
if (!filter(id)) {
|
||||
return;
|
||||
}
|
||||
const { filename } = (0, url_1.parseVueRequest)(id);
|
||||
if (!constants_1.EXTNAME_VUE_TEMPLATE.includes(path_1.default.extname(filename))) {
|
||||
return;
|
||||
}
|
||||
// 替换 UTS custom element import placeholder
|
||||
// 目前主要是iOS和harmony,Android不需要
|
||||
const hasUTSCustomElementImport = code.includes(transformUTSComponent_1.UTS_CUSTOM_ELEMENT_IMPORT_PLACEHOLDER);
|
||||
if (hasUTSCustomElementImport) {
|
||||
code = code.replace(new RegExp(`${transformUTSComponent_1.UTS_CUSTOM_ELEMENT_IMPORT_PLACEHOLDER} from `, 'g'), '');
|
||||
}
|
||||
if (!code.includes('_resolveComponent')) {
|
||||
if (hasUTSCustomElementImport) {
|
||||
return {
|
||||
code,
|
||||
map: {
|
||||
mappings: '',
|
||||
},
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
let i = 0;
|
||||
const importDeclarations = [];
|
||||
code = code.replace(/_resolveComponent\("(.+?)"(, true)?\)/g, (str, name) => {
|
||||
if (name && !name.startsWith('_')) {
|
||||
const source = (0, easycom_1.matchEasycom)(name);
|
||||
if (source) {
|
||||
// 处理easycom组件优先级
|
||||
return (0, easycom_1.genResolveEasycomCode)(importDeclarations, str, (0, easycom_1.addImportDeclaration)(importDeclarations, `__easycom_${i++}`, source, source.includes('uts-proxy')
|
||||
? (0, shared_1.capitalize)((0, shared_1.camelize)(name)) + 'Component'
|
||||
: source.includes('uni_helpers')
|
||||
? (0, shared_1.capitalize)((0, shared_1.camelize)(name))
|
||||
: ''));
|
||||
}
|
||||
else {
|
||||
const utsCustomElement = (0, uts_1.getUTSCustomElement)(name);
|
||||
if (utsCustomElement) {
|
||||
(0, easycom_1.addImportDeclaration)(importDeclarations, '', utsCustomElement.source, '');
|
||||
return `'${name}'`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return str;
|
||||
});
|
||||
if (importDeclarations.length) {
|
||||
code = importDeclarations.join('') + code;
|
||||
}
|
||||
return {
|
||||
code,
|
||||
map: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniEasycomPlugin = uniEasycomPlugin;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
export * from './cssScoped';
|
||||
export * from './copy';
|
||||
export * from './inject';
|
||||
export * from './mainJs';
|
||||
export * from './jsonJs';
|
||||
export * from './console';
|
||||
export * from './dynamicImportPolyfill';
|
||||
export * from './uts/uni_modules';
|
||||
export * from './uts/uvue';
|
||||
export * from './uts/ext-api';
|
||||
export * from './easycom';
|
||||
export * from './json';
|
||||
export * from './pre';
|
||||
export * from './sourceMap';
|
||||
export { uniViteSfcSrcImportPlugin } from './sfc';
|
||||
export { assetPlugin, parseAssets, getAssetHash } from './vitejs/plugins/asset';
|
||||
export { isCSSRequest, cssPlugin, cssPostPlugin, minifyCSS, cssLangRE, commonjsProxyRE, rewriteScssReadFileSync, getCssDepMap, } from './vitejs/plugins/css';
|
||||
export { generateCodeFrame, locToStartAndEnd, offsetToStartAndEnd, } from './vitejs/utils';
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.offsetToStartAndEnd = exports.locToStartAndEnd = exports.generateCodeFrame = exports.getCssDepMap = exports.rewriteScssReadFileSync = exports.commonjsProxyRE = exports.cssLangRE = exports.minifyCSS = exports.cssPostPlugin = exports.cssPlugin = exports.isCSSRequest = exports.getAssetHash = exports.parseAssets = exports.assetPlugin = exports.uniViteSfcSrcImportPlugin = void 0;
|
||||
__exportStar(require("./cssScoped"), exports);
|
||||
__exportStar(require("./copy"), exports);
|
||||
__exportStar(require("./inject"), exports);
|
||||
__exportStar(require("./mainJs"), exports);
|
||||
__exportStar(require("./jsonJs"), exports);
|
||||
__exportStar(require("./console"), exports);
|
||||
__exportStar(require("./dynamicImportPolyfill"), exports);
|
||||
__exportStar(require("./uts/uni_modules"), exports);
|
||||
__exportStar(require("./uts/uvue"), exports);
|
||||
__exportStar(require("./uts/ext-api"), exports);
|
||||
__exportStar(require("./easycom"), exports);
|
||||
__exportStar(require("./json"), exports);
|
||||
__exportStar(require("./pre"), exports);
|
||||
__exportStar(require("./sourceMap"), exports);
|
||||
var sfc_1 = require("./sfc");
|
||||
Object.defineProperty(exports, "uniViteSfcSrcImportPlugin", { enumerable: true, get: function () { return sfc_1.uniViteSfcSrcImportPlugin; } });
|
||||
var asset_1 = require("./vitejs/plugins/asset");
|
||||
Object.defineProperty(exports, "assetPlugin", { enumerable: true, get: function () { return asset_1.assetPlugin; } });
|
||||
Object.defineProperty(exports, "parseAssets", { enumerable: true, get: function () { return asset_1.parseAssets; } });
|
||||
Object.defineProperty(exports, "getAssetHash", { enumerable: true, get: function () { return asset_1.getAssetHash; } });
|
||||
var css_1 = require("./vitejs/plugins/css");
|
||||
Object.defineProperty(exports, "isCSSRequest", { enumerable: true, get: function () { return css_1.isCSSRequest; } });
|
||||
Object.defineProperty(exports, "cssPlugin", { enumerable: true, get: function () { return css_1.cssPlugin; } });
|
||||
Object.defineProperty(exports, "cssPostPlugin", { enumerable: true, get: function () { return css_1.cssPostPlugin; } });
|
||||
Object.defineProperty(exports, "minifyCSS", { enumerable: true, get: function () { return css_1.minifyCSS; } });
|
||||
Object.defineProperty(exports, "cssLangRE", { enumerable: true, get: function () { return css_1.cssLangRE; } });
|
||||
Object.defineProperty(exports, "commonjsProxyRE", { enumerable: true, get: function () { return css_1.commonjsProxyRE; } });
|
||||
Object.defineProperty(exports, "rewriteScssReadFileSync", { enumerable: true, get: function () { return css_1.rewriteScssReadFileSync; } });
|
||||
Object.defineProperty(exports, "getCssDepMap", { enumerable: true, get: function () { return css_1.getCssDepMap; } });
|
||||
var utils_1 = require("./vitejs/utils");
|
||||
Object.defineProperty(exports, "generateCodeFrame", { enumerable: true, get: function () { return utils_1.generateCodeFrame; } });
|
||||
Object.defineProperty(exports, "locToStartAndEnd", { enumerable: true, get: function () { return utils_1.locToStartAndEnd; } });
|
||||
Object.defineProperty(exports, "offsetToStartAndEnd", { enumerable: true, get: function () { return utils_1.offsetToStartAndEnd; } });
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import { type FilterPattern } from '@rollup/pluginutils';
|
||||
type Injectment = string | [string, string];
|
||||
export interface InjectOptions {
|
||||
enforce?: 'pre' | 'post';
|
||||
sourceMap?: boolean;
|
||||
callback?: (imports: Map<any, any>, mod: [string, string]) => void;
|
||||
include?: FilterPattern;
|
||||
exclude?: FilterPattern;
|
||||
[str: string]: Injectment | FilterPattern | Boolean | Function | undefined;
|
||||
}
|
||||
export declare function uniViteInjectPlugin(name: string, options: InjectOptions): Plugin;
|
||||
export {};
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniViteInjectPlugin = void 0;
|
||||
const path_1 = require("path");
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const pluginutils_1 = require("@rollup/pluginutils");
|
||||
const estree_walker_1 = require("estree-walker");
|
||||
const shared_1 = require("@vue/shared");
|
||||
const magic_string_1 = __importDefault(require("magic-string"));
|
||||
const utils_1 = require("../utils");
|
||||
const debugInject = (0, debug_1.default)('uni:inject');
|
||||
// const debugInjectTry = debug('uni:inject-try')
|
||||
function uniViteInjectPlugin(name, options) {
|
||||
if (!options)
|
||||
throw new Error('Missing options');
|
||||
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
|
||||
const modules = (0, shared_1.extend)({}, options);
|
||||
delete modules.include;
|
||||
delete modules.exclude;
|
||||
delete modules.sourceMap;
|
||||
delete modules.callback;
|
||||
const reassignments = new Set();
|
||||
const modulesMap = new Map();
|
||||
const namespaceModulesMap = new Map();
|
||||
Object.keys(modules).forEach((name) => {
|
||||
if (name.endsWith('.')) {
|
||||
namespaceModulesMap.set(name, modules[name]);
|
||||
}
|
||||
modulesMap.set(name, modules[name]);
|
||||
});
|
||||
const hasNamespace = namespaceModulesMap.size > 0;
|
||||
// Fix paths on Windows
|
||||
if (path_1.sep !== '/') {
|
||||
normalizeModulesMap(modulesMap);
|
||||
normalizeModulesMap(namespaceModulesMap);
|
||||
}
|
||||
const firstpass = new RegExp(`(?:${Array.from(modulesMap.keys()).map(escape).join('|')})`, 'g');
|
||||
const sourceMap = options.sourceMap !== false;
|
||||
const callback = options.callback;
|
||||
return {
|
||||
name,
|
||||
// 确保在 commonjs 之后,否则会混合 es6 module 与 cjs 的代码,导致 commonjs 失效
|
||||
enforce: options.enforce ?? 'post',
|
||||
transform(code, id) {
|
||||
if (!filter(id))
|
||||
return null;
|
||||
if (!(0, utils_1.isJsFile)(id))
|
||||
return null;
|
||||
// debugInjectTry(id)
|
||||
if (code.search(firstpass) === -1)
|
||||
return null;
|
||||
if (path_1.sep !== '/')
|
||||
id = id.split(path_1.sep).join('/');
|
||||
const ast = this.parse(code);
|
||||
const imports = new Set();
|
||||
ast.body.forEach((node) => {
|
||||
if (node.type === 'ImportDeclaration') {
|
||||
node.specifiers.forEach((specifier) => {
|
||||
imports.add(specifier.local.name);
|
||||
});
|
||||
}
|
||||
});
|
||||
// analyse scopes
|
||||
let scope = (0, pluginutils_1.attachScopes)(ast, 'scope');
|
||||
const magicString = new magic_string_1.default(code);
|
||||
const newImports = new Map();
|
||||
function handleReference(node, name, keypath, parent) {
|
||||
let mod = modulesMap.get(keypath);
|
||||
if (!mod && hasNamespace) {
|
||||
const mods = keypath.split('.');
|
||||
if (mods.length === 2) {
|
||||
mod = namespaceModulesMap.get(mods[0] + '.');
|
||||
if (mod) {
|
||||
if ((0, shared_1.isArray)(mod)) {
|
||||
const testFn = mod[1];
|
||||
if (testFn(mods[1])) {
|
||||
mod = [mod[0], mods[1]];
|
||||
}
|
||||
else {
|
||||
mod = undefined;
|
||||
}
|
||||
}
|
||||
else {
|
||||
mod = [mod, mods[1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (mod && !imports.has(name) && !scope.contains(name)) {
|
||||
if ((0, shared_1.isString)(mod))
|
||||
mod = [mod, 'default'];
|
||||
if (mod[0] === id)
|
||||
return false;
|
||||
const hash = `${keypath}:${mod[0]}:${mod[1]}`;
|
||||
// 当 API 被覆盖定义后,不再摇树
|
||||
if (reassignments.has(hash)) {
|
||||
return false;
|
||||
}
|
||||
if (parent &&
|
||||
(0, utils_1.isAssignmentExpression)(parent) &&
|
||||
parent.left === node) {
|
||||
reassignments.add(hash);
|
||||
return false;
|
||||
}
|
||||
const importLocalName = name === keypath ? name : (0, pluginutils_1.makeLegalIdentifier)(`$inject_${keypath}`);
|
||||
if (!newImports.has(hash)) {
|
||||
if (mod[1] === '*') {
|
||||
newImports.set(hash, `import * as ${importLocalName} from '${mod[0]}';`);
|
||||
}
|
||||
else {
|
||||
newImports.set(hash, `import { ${mod[1]} as ${importLocalName} } from '${mod[0]}';`);
|
||||
callback && callback(newImports, mod);
|
||||
}
|
||||
}
|
||||
if (name !== keypath) {
|
||||
magicString.overwrite(node.start, node.end, importLocalName, {
|
||||
storeName: true,
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
(0, estree_walker_1.walk)(ast, {
|
||||
enter(node, parent) {
|
||||
if (sourceMap) {
|
||||
magicString.addSourcemapLocation(node.start);
|
||||
magicString.addSourcemapLocation(node.end);
|
||||
}
|
||||
if (node.scope) {
|
||||
scope = node.scope;
|
||||
}
|
||||
if ((0, utils_1.isProperty)(node) && node.shorthand) {
|
||||
const { name } = node.key;
|
||||
handleReference(node, name, name);
|
||||
this.skip();
|
||||
return;
|
||||
}
|
||||
if ((0, utils_1.isReference)(node, parent)) {
|
||||
const { name, keypath } = flatten(node);
|
||||
const handled = handleReference(node, name, keypath, parent);
|
||||
if (handled) {
|
||||
this.skip();
|
||||
}
|
||||
}
|
||||
},
|
||||
leave(node) {
|
||||
if (node.scope) {
|
||||
scope = scope.parent;
|
||||
}
|
||||
},
|
||||
});
|
||||
debugInject(id, newImports.size);
|
||||
if (newImports.size === 0) {
|
||||
return {
|
||||
code,
|
||||
// 不能返回 ast ,否则会导致代码不能被再次修改
|
||||
// 比如 App.vue 中,console.log('uniCloud') 触发了 inject 检测,检测完,发现不需要
|
||||
// 此时返回 ast,会导致 import { setupApp } from '@dcloudio/uni-h5' 不会被编译
|
||||
// ast
|
||||
map: null,
|
||||
};
|
||||
}
|
||||
const importBlock = Array.from(newImports.values()).join('\n\n');
|
||||
magicString.prepend(`${importBlock}\n\n`);
|
||||
return {
|
||||
code: magicString.toString(),
|
||||
map: sourceMap ? magicString.generateMap({ hires: true }) : null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniViteInjectPlugin = uniViteInjectPlugin;
|
||||
const escape = (str) => str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
|
||||
const flatten = (startNode) => {
|
||||
const parts = [];
|
||||
let node = startNode;
|
||||
while ((0, utils_1.isMemberExpression)(node)) {
|
||||
parts.unshift(node.property.name);
|
||||
node = node.object;
|
||||
}
|
||||
const { name } = node;
|
||||
parts.unshift(name);
|
||||
return { name, keypath: parts.join('.') };
|
||||
};
|
||||
function normalizeModulesMap(modulesMap) {
|
||||
modulesMap.forEach((mod, key) => {
|
||||
modulesMap.set(key, (0, shared_1.isArray)(mod)
|
||||
? [mod[0].split(path_1.sep).join('/'), mod[1]]
|
||||
: mod.split(path_1.sep).join('/'));
|
||||
});
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniJsonPlugin(): Plugin;
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniJsonPlugin = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const json_1 = require("../../json");
|
||||
const preprocess_1 = require("../../preprocess");
|
||||
const utils_1 = require("../utils");
|
||||
function uniJsonPlugin() {
|
||||
return {
|
||||
name: 'uni:json',
|
||||
enforce: 'pre',
|
||||
transform(code, id) {
|
||||
// 如果已经被其他插件处理过了,就不再处理,比如 commonjs 插件,ICAPRegistrar.json?commonjs-external
|
||||
if (id.startsWith('\0')) {
|
||||
return;
|
||||
}
|
||||
if (path_1.default.extname((0, utils_1.parseVueRequest)(id).filename) !== '.json') {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
code: JSON.stringify((0, json_1.parseJson)((0, preprocess_1.preJson)(code, id), false, id), null, 2),
|
||||
map: {
|
||||
mappings: '',
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniJsonPlugin = uniJsonPlugin;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { CreateUniViteFilterPlugin } from '../utils/plugin';
|
||||
export declare const defineUniPagesJsonPlugin: (createVitePlugin: CreateUniViteFilterPlugin) => import("vite").Plugin<any>;
|
||||
export declare const defineUniManifestJsonPlugin: (createVitePlugin: CreateUniViteFilterPlugin) => import("vite").Plugin<any>;
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.defineUniManifestJsonPlugin = exports.defineUniPagesJsonPlugin = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const constants_1 = require("../../constants");
|
||||
const utils_1 = require("../../utils");
|
||||
exports.defineUniPagesJsonPlugin = createDefineJsonJsPlugin('pages.json');
|
||||
exports.defineUniManifestJsonPlugin = createDefineJsonJsPlugin('manifest.json');
|
||||
function createDefineJsonJsPlugin(name) {
|
||||
const JSON_JS = constants_1.JSON_JS_MAP[name];
|
||||
return function (createVitePlugin) {
|
||||
const opts = {
|
||||
resolvedConfig: {},
|
||||
filter(id) {
|
||||
return id.endsWith(JSON_JS);
|
||||
},
|
||||
};
|
||||
const plugin = createVitePlugin(opts);
|
||||
const origLoad = plugin.load;
|
||||
const origResolveId = plugin.resolveId;
|
||||
const origConfigResolved = plugin.configResolved;
|
||||
let jsonPath = '';
|
||||
let jsonJsPath = '';
|
||||
plugin.resolveId = function (id, importer, options) {
|
||||
const res = origResolveId && origResolveId.call(this, id, importer, options);
|
||||
if (res) {
|
||||
return res;
|
||||
}
|
||||
if (id.endsWith(JSON_JS)) {
|
||||
return jsonJsPath;
|
||||
}
|
||||
};
|
||||
plugin.configResolved = function (config) {
|
||||
opts.resolvedConfig = config;
|
||||
jsonPath = (0, utils_1.normalizePath)(path_1.default.join(process.env.UNI_INPUT_DIR, name));
|
||||
jsonJsPath = (0, utils_1.normalizePath)(path_1.default.join(process.env.UNI_INPUT_DIR, JSON_JS));
|
||||
return origConfigResolved && origConfigResolved(config);
|
||||
};
|
||||
plugin.load = function (id, ssr) {
|
||||
const res = origLoad && origLoad.call(this, id, ssr);
|
||||
if (res) {
|
||||
return res;
|
||||
}
|
||||
if (!opts.filter(id)) {
|
||||
return;
|
||||
}
|
||||
return fs_1.default.readFileSync(jsonPath, 'utf8');
|
||||
};
|
||||
return plugin;
|
||||
};
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { CreateUniViteFilterPlugin } from '../utils/plugin';
|
||||
export declare function defineUniMainJsPlugin(createUniMainJsPlugin: CreateUniViteFilterPlugin): import("vite").Plugin<any>;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.defineUniMainJsPlugin = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const utils_1 = require("../../utils");
|
||||
function defineUniMainJsPlugin(createUniMainJsPlugin) {
|
||||
const opts = {
|
||||
resolvedConfig: {},
|
||||
filter(id) {
|
||||
return id === mainJsPath || id === mainTsPath || id === mainUTsPath;
|
||||
},
|
||||
};
|
||||
const plugin = createUniMainJsPlugin(opts);
|
||||
const origConfigResolved = plugin.configResolved;
|
||||
let mainJsPath = '';
|
||||
let mainTsPath = '';
|
||||
let mainUTsPath = '';
|
||||
plugin.configResolved = function (config) {
|
||||
opts.resolvedConfig = config;
|
||||
const mainPath = (0, utils_1.normalizePath)(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'main'));
|
||||
mainJsPath = mainPath + '.js';
|
||||
mainTsPath = mainPath + '.ts';
|
||||
mainUTsPath = mainPath + '.uts';
|
||||
return origConfigResolved && origConfigResolved(config);
|
||||
};
|
||||
return plugin;
|
||||
}
|
||||
exports.defineUniMainJsPlugin = defineUniMainJsPlugin;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
import { type FilterPattern } from '@rollup/pluginutils';
|
||||
export declare function uniPrePlugin(config: ResolvedConfig, options: {
|
||||
include?: FilterPattern;
|
||||
exclude?: FilterPattern;
|
||||
}): Plugin;
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniPrePlugin = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const pluginutils_1 = require("@rollup/pluginutils");
|
||||
const constants_1 = require("../../constants");
|
||||
const preprocess_1 = require("../../preprocess");
|
||||
const utils_1 = require("../utils");
|
||||
const debugPreJs = (0, debug_1.default)('uni:pre-js');
|
||||
const debugPreHtml = (0, debug_1.default)('uni:pre-html');
|
||||
// const debugPreJsTry = debug('uni:pre-js-try')
|
||||
function uniPrePlugin(config, options) {
|
||||
const isX = process.env.UNI_APP_X === 'true';
|
||||
const PRE_JS_EXTNAME = ['.json', '.css']
|
||||
.concat(isX ? constants_1.X_EXTNAME_VUE : constants_1.EXTNAME_VUE)
|
||||
.concat(constants_1.EXTNAME_JS); // 因为 1.0 也会使用 uts uni_modules,所以 EXTNAME_JS 直接包含了 .uts 后缀
|
||||
const PRE_HTML_EXTNAME = isX ? constants_1.X_EXTNAME_VUE : constants_1.EXTNAME_VUE;
|
||||
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
|
||||
const isNVue = config.nvue;
|
||||
const preJsFile = isNVue ? preprocess_1.preNVueJs : preprocess_1.preJs;
|
||||
const preHtmlFile = isNVue ? preprocess_1.preNVueHtml : preprocess_1.preHtml;
|
||||
return {
|
||||
name: 'uni:pre',
|
||||
transform(code, id) {
|
||||
if (!filter(id)) {
|
||||
return;
|
||||
}
|
||||
const { filename, query } = (0, utils_1.parseVueRequest)(id);
|
||||
const extname = path_1.default.extname(filename);
|
||||
const isHtml = query.type === 'template' || PRE_HTML_EXTNAME.includes(extname);
|
||||
const isJs = PRE_JS_EXTNAME.includes(extname);
|
||||
const isPre = isHtml || isJs;
|
||||
if (isPre) {
|
||||
// debugPreJsTry(id)
|
||||
}
|
||||
const hasEndif = isPre && code.includes('#endif');
|
||||
if (!hasEndif) {
|
||||
return;
|
||||
}
|
||||
if (isHtml) {
|
||||
code = preHtmlFile(code, id);
|
||||
debugPreHtml(id);
|
||||
}
|
||||
if (isJs) {
|
||||
code = preJsFile(code, id);
|
||||
debugPreJs(id);
|
||||
}
|
||||
return {
|
||||
code,
|
||||
map: (0, utils_1.withSourcemap)(config) ? this.getCombinedSourcemap() : null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniPrePlugin = uniPrePlugin;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function isSrcImport(code: string): boolean;
|
||||
export declare function isSrcImportVue(code: string): boolean;
|
||||
export declare function uniViteSfcSrcImportPlugin({ onlyVue }?: {
|
||||
onlyVue: boolean;
|
||||
}): 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.uniViteSfcSrcImportPlugin = exports.isSrcImportVue = exports.isSrcImport = void 0;
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const magic_string_1 = __importDefault(require("magic-string"));
|
||||
const vue_1 = require("../../vue");
|
||||
const utils_1 = require("../utils");
|
||||
const preprocess_1 = require("../../preprocess");
|
||||
const SRC_IMPORT_RE = /<(template|script|style)[^>]*src\s*=\s*["']([^"']+)["'][^>]*>/;
|
||||
const SRC_IMPORT_VUE_RE = /<(template|script|style)[^>]*src\s*=\s*["'](.*\.uvue|.*\.vue)["'][^>]*>/;
|
||||
function isSrcImport(code) {
|
||||
return SRC_IMPORT_RE.test(code);
|
||||
}
|
||||
exports.isSrcImport = isSrcImport;
|
||||
function isSrcImportVue(code) {
|
||||
return SRC_IMPORT_VUE_RE.test(code);
|
||||
}
|
||||
exports.isSrcImportVue = isSrcImportVue;
|
||||
function uniViteSfcSrcImportPlugin({ onlyVue } = { onlyVue: true }) {
|
||||
const { parse } = require('@vue/compiler-sfc');
|
||||
const hasImport = onlyVue ? isSrcImportVue : isSrcImport;
|
||||
const isValidSrc = onlyVue ? vue_1.isVueSfcFile : () => true;
|
||||
return {
|
||||
name: 'uni:sfc-src-import',
|
||||
async transform(code, id) {
|
||||
if (!(0, vue_1.isVueSfcFile)(id)) {
|
||||
return;
|
||||
}
|
||||
if (!hasImport(code)) {
|
||||
return;
|
||||
}
|
||||
const s = new magic_string_1.default(code);
|
||||
const sourceMap = process.env.NODE_ENV === 'development';
|
||||
const createDescriptor = (filename, code, from) => {
|
||||
if (from === 'vue' || (0, vue_1.isVueSfcFile)(filename)) {
|
||||
const { descriptor, errors } = parse(code, {
|
||||
filename,
|
||||
sourceMap,
|
||||
});
|
||||
errors.forEach((error) => this.error((0, utils_1.createRollupError)('', filename, error, code)));
|
||||
return descriptor;
|
||||
}
|
||||
else {
|
||||
const descriptor = {
|
||||
filename,
|
||||
source: fs_extra_1.default.readFileSync(filename, 'utf-8'),
|
||||
template: null,
|
||||
script: null,
|
||||
scriptSetup: null,
|
||||
styles: [],
|
||||
customBlocks: [],
|
||||
};
|
||||
if (from === 'template') {
|
||||
descriptor.template = {
|
||||
content: descriptor.source,
|
||||
};
|
||||
}
|
||||
else if (from === 'script') {
|
||||
descriptor.script = {
|
||||
content: descriptor.source,
|
||||
};
|
||||
}
|
||||
else if (from === 'style') {
|
||||
descriptor.styles = [
|
||||
{
|
||||
content: descriptor.source,
|
||||
},
|
||||
];
|
||||
}
|
||||
return descriptor;
|
||||
}
|
||||
};
|
||||
const descriptor = createDescriptor(id, code, 'vue');
|
||||
const cache = new Map();
|
||||
const getSrcDescriptor = async (src, from) => {
|
||||
if (cache.has(src)) {
|
||||
return cache.get(src);
|
||||
}
|
||||
const resolved = await this.resolve(src, descriptor.filename);
|
||||
if (resolved) {
|
||||
const filename = resolved.id;
|
||||
const srcDescriptor = createDescriptor(filename, (0, preprocess_1.preUVueJs)((0, preprocess_1.preUVueHtml)(fs_extra_1.default.readFileSync(filename, 'utf-8'), filename), filename), from);
|
||||
cache.set(src, srcDescriptor);
|
||||
this.addWatchFile(filename);
|
||||
return srcDescriptor;
|
||||
}
|
||||
};
|
||||
if (descriptor.template?.src && isValidSrc(descriptor.template.src)) {
|
||||
const srcDescriptor = await getSrcDescriptor(descriptor.template.src, 'template');
|
||||
if (srcDescriptor && srcDescriptor.template?.content) {
|
||||
overwriteContent(s, descriptor.template.loc, srcDescriptor.template.content);
|
||||
}
|
||||
}
|
||||
if (descriptor.script?.src && isValidSrc(descriptor.script.src)) {
|
||||
const srcDescriptor = await getSrcDescriptor(descriptor.script.src, 'script');
|
||||
if (srcDescriptor && srcDescriptor.script?.content) {
|
||||
overwriteContent(s, descriptor.script.loc, srcDescriptor.script.content);
|
||||
}
|
||||
}
|
||||
for (const style of descriptor.styles) {
|
||||
if (style.src && isValidSrc(style.src)) {
|
||||
const srcDescriptor = await getSrcDescriptor(style.src, 'style');
|
||||
if (srcDescriptor && srcDescriptor.styles[0]) {
|
||||
overwriteContent(s, style.loc, srcDescriptor.styles[0].content);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!s.hasChanged()) {
|
||||
return;
|
||||
}
|
||||
// 移除所有的 src 属性
|
||||
const regex = /(<(template|script|style)[^>]*)src\s*=\s*["']([^"']+)["']([^>]*>)/g;
|
||||
let match;
|
||||
while ((match = regex.exec(code))) {
|
||||
const [_, start, _tag, _src, end] = match;
|
||||
s.overwrite(match.index, match.index + _.length, `${start}${end}`);
|
||||
}
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: sourceMap ? s.generateMap({ hires: true }) : { mappings: '' },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniViteSfcSrcImportPlugin = uniViteSfcSrcImportPlugin;
|
||||
function overwriteContent(s, loc, content) {
|
||||
if (loc.start.offset === loc.end.offset) {
|
||||
s.appendRight(loc.start.offset, content);
|
||||
}
|
||||
else {
|
||||
s.overwrite(loc.start.offset, loc.end.offset, content);
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniSourceMapPlugin(options: {
|
||||
sourceMapDir: string;
|
||||
relativeSourceMapDir: string;
|
||||
}): Plugin;
|
||||
Generated
Vendored
+70
@@ -0,0 +1,70 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniSourceMapPlugin = void 0;
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const crypto_1 = __importDefault(require("crypto"));
|
||||
const utils_1 = require("../../utils");
|
||||
const debugSourceMap = (0, debug_1.default)('uni:sourcemap');
|
||||
function uniSourceMapPlugin(options) {
|
||||
// 使用 WeakMap 存储文件内容的哈希值,避免内存泄漏
|
||||
const contentHashMap = new Map();
|
||||
return {
|
||||
name: 'uni:sourcemap',
|
||||
enforce: 'post',
|
||||
async generateBundle(_, bundle) {
|
||||
if (!(0, utils_1.enableSourceMap)()) {
|
||||
return;
|
||||
}
|
||||
// 批量处理所有 sourcemap 文件
|
||||
const tasks = Object.entries(bundle)
|
||||
.filter(([file]) => file.endsWith('.js.map'))
|
||||
.map(async ([file, asset]) => {
|
||||
const source = asset.source;
|
||||
const targetPath = path_1.default.resolve(options.sourceMapDir, file);
|
||||
// 快速计算内容哈希
|
||||
const hash = crypto_1.default
|
||||
.createHash('md5') // xxhash 比 md5 快很多
|
||||
.update(source)
|
||||
.digest('hex');
|
||||
let needsUpdate = true;
|
||||
try {
|
||||
// 使用 stat 检查文件是否存在,比 pathExists 更快
|
||||
const stat = await fs_extra_1.default.stat(targetPath);
|
||||
if (stat.isFile()) {
|
||||
const oldHash = contentHashMap.get(file);
|
||||
needsUpdate = !oldHash || oldHash !== hash;
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// 文件不存在,需要写入
|
||||
needsUpdate = true;
|
||||
}
|
||||
if (needsUpdate) {
|
||||
await fs_extra_1.default.outputFile(targetPath, source);
|
||||
contentHashMap.set(file, hash);
|
||||
debugSourceMap.enabled &&
|
||||
debugSourceMap('write sourcemap file %s', file);
|
||||
}
|
||||
else {
|
||||
debugSourceMap.enabled &&
|
||||
debugSourceMap('skip unchanged sourcemap file %s', file);
|
||||
}
|
||||
// 更新引用
|
||||
const jsFile = file.replace('.js.map', '.js');
|
||||
const outputChunk = bundle[jsFile];
|
||||
if (outputChunk) {
|
||||
outputChunk.code = outputChunk.code.replace(/\/\/# sourceMappingURL=.*/, `//# sourceMappingURL=${(0, utils_1.normalizePath)(path_1.default.relative(file, options.relativeSourceMapDir))}/${file}`);
|
||||
}
|
||||
delete bundle[file];
|
||||
});
|
||||
// 使用 Promise.all 并行处理所有文件
|
||||
await Promise.all(tasks);
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniSourceMapPlugin = uniSourceMapPlugin;
|
||||
Generated
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import { type Injects, parseUniExtApis } from '../../../uni_modules';
|
||||
export declare const parseUniExtApisOnce: typeof parseUniExtApis;
|
||||
export declare function uniUTSExtApiReplace(): Plugin;
|
||||
/**
|
||||
* { 'uni.getBatteryInfo': ['@/uni_modules/uni-getbatteryinfo/utssdk/web/index.uts','getBatteryInfo'] }
|
||||
* { '@/uni_modules/uni-getbatteryinfo/utssdk/web/index.ts': [['getBatteryInfo', 'uni_getBatteryInfo']] }
|
||||
* @param injects
|
||||
*/
|
||||
export declare function injectsToAutoImports(injects: Injects): {
|
||||
from: string;
|
||||
imports: [string, string][];
|
||||
}[];
|
||||
Generated
Vendored
+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.injectsToAutoImports = exports.uniUTSExtApiReplace = exports.parseUniExtApisOnce = void 0;
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_shared_1 = require("@dcloudio/uni-shared");
|
||||
const vite_1 = __importDefault(require("unplugin-auto-import/vite"));
|
||||
const uni_modules_1 = require("../../../uni_modules");
|
||||
const url_1 = require("../../utils/url");
|
||||
const escape = (str) => str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
|
||||
exports.parseUniExtApisOnce = (0, uni_shared_1.once)(uni_modules_1.parseUniExtApis);
|
||||
function uniUTSExtApiReplace() {
|
||||
const injects = (0, exports.parseUniExtApisOnce)(true, process.env.UNI_UTS_PLATFORM, process.env.UNI_UTS_TARGET_LANGUAGE);
|
||||
const injectApis = Object.keys(injects);
|
||||
const firstPass = new RegExp(`(?:${injectApis.map(escape).join('|')})`, 'g');
|
||||
return {
|
||||
name: 'uni:uts-ext-api-replace',
|
||||
configResolved(config) {
|
||||
const index = config.plugins.findIndex((p) => p.name === 'uts');
|
||||
if (index > -1) {
|
||||
if (Object.keys(injects).length) {
|
||||
// @ts-expect-error
|
||||
config.plugins.splice(index, 0, (0, vite_1.default)({
|
||||
include: [/\.[u]?ts$/, /\.[u]?vue/],
|
||||
exclude: [/[\\/]\.git[\\/]/],
|
||||
imports: injectsToAutoImports(injects),
|
||||
dts: false,
|
||||
}));
|
||||
}
|
||||
}
|
||||
},
|
||||
transform(code, id) {
|
||||
if (!injectApis.length) {
|
||||
return;
|
||||
}
|
||||
if (!(0, url_1.isJsFile)(id)) {
|
||||
return;
|
||||
}
|
||||
if (code.search(firstPass) === -1) {
|
||||
return;
|
||||
}
|
||||
injectApis.forEach((api) => {
|
||||
code = code.replaceAll(api, api.replace('.', '_'));
|
||||
});
|
||||
return {
|
||||
code,
|
||||
map: { mappings: '' },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniUTSExtApiReplace = uniUTSExtApiReplace;
|
||||
/**
|
||||
* { 'uni.getBatteryInfo': ['@/uni_modules/uni-getbatteryinfo/utssdk/web/index.uts','getBatteryInfo'] }
|
||||
* { '@/uni_modules/uni-getbatteryinfo/utssdk/web/index.ts': [['getBatteryInfo', 'uni_getBatteryInfo']] }
|
||||
* @param injects
|
||||
*/
|
||||
function injectsToAutoImports(injects) {
|
||||
const autoImports = {};
|
||||
Object.keys(injects).forEach((api) => {
|
||||
const options = injects[api];
|
||||
if ((0, shared_1.isArray)(options) && options.length >= 2) {
|
||||
const source = options[0];
|
||||
const name = options[1];
|
||||
if (!autoImports[source]) {
|
||||
autoImports[source] = [];
|
||||
}
|
||||
autoImports[source].push([name, api.replace('.', '_')]);
|
||||
}
|
||||
});
|
||||
return Object.keys(autoImports).map((source) => {
|
||||
return {
|
||||
from: source,
|
||||
imports: autoImports[source],
|
||||
};
|
||||
});
|
||||
}
|
||||
exports.injectsToAutoImports = injectsToAutoImports;
|
||||
Generated
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { SyncUniModulesFilePreprocessor } from '@dcloudio/uni-uts-v1';
|
||||
export declare function rewriteUniModulesConsoleExpr(fileName: string, content: string): string;
|
||||
export declare function createAppAndroidUniModulesSyncFilePreprocessorOnce(isX: boolean): SyncUniModulesFilePreprocessor;
|
||||
export declare function createAppIosUniModulesSyncFilePreprocessorOnce(isX: boolean): SyncUniModulesFilePreprocessor;
|
||||
export declare function createAppHarmonyUniModulesSyncFilePreprocessorOnce(isX: boolean): SyncUniModulesFilePreprocessor;
|
||||
interface UniUTSPluginOptions {
|
||||
x?: boolean;
|
||||
extApis?: Record<string, [string, string]>;
|
||||
isSingleThread?: boolean;
|
||||
}
|
||||
export declare function getCurrentCompiledUTSPlugins(): Set<string>;
|
||||
export declare function getCurrentCompiledUTSProviders(): Set<string>;
|
||||
export declare function uniUTSAppUniModulesPlugin(options?: UniUTSPluginOptions): Plugin;
|
||||
export declare function buildUniExtApis(): Promise<void>;
|
||||
export declare function resolveExtApiProvider(pkg: Record<string, any>): {
|
||||
name?: string | undefined;
|
||||
plugin?: string | undefined;
|
||||
service: string;
|
||||
servicePlugin: string;
|
||||
} | undefined;
|
||||
export declare function uniDecryptUniModulesPlugin(): Plugin;
|
||||
export {};
|
||||
Generated
Vendored
+582
@@ -0,0 +1,582 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniDecryptUniModulesPlugin = exports.resolveExtApiProvider = exports.buildUniExtApis = exports.uniUTSAppUniModulesPlugin = exports.getCurrentCompiledUTSProviders = exports.getCurrentCompiledUTSPlugins = exports.createAppHarmonyUniModulesSyncFilePreprocessorOnce = exports.createAppIosUniModulesSyncFilePreprocessorOnce = exports.createAppAndroidUniModulesSyncFilePreprocessorOnce = exports.rewriteUniModulesConsoleExpr = void 0;
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_shared_1 = require("@dcloudio/uni-shared");
|
||||
const pluginutils_1 = require("@rollup/pluginutils");
|
||||
const uts_1 = require("../../../uts");
|
||||
const utils_1 = require("../../utils");
|
||||
const uni_modules_1 = require("../../../uni_modules");
|
||||
const uni_modules_cloud_1 = require("../../../uni_modules.cloud");
|
||||
const utils_2 = require("../../../utils");
|
||||
const json_1 = require("../../../json");
|
||||
const fs_1 = require("../../../fs");
|
||||
const context_1 = require("../../../preprocess/context");
|
||||
const hbx_1 = require("../../../hbx");
|
||||
const console_1 = require("../../../logs/console");
|
||||
/* eslint-disable no-restricted-globals */
|
||||
const { preprocess } = require('../../../../lib/preprocess');
|
||||
function rewriteUniModulesConsoleExpr(fileName, content) {
|
||||
// 仅开发模式补充console.log的at信息
|
||||
if (process.env.NODE_ENV !== 'development') {
|
||||
return content;
|
||||
}
|
||||
if (content.includes('console.')) {
|
||||
return (0, console_1.rewriteConsoleExpr)('__f__', '', (0, utils_2.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, fileName.split('?')[0])), content, false).code;
|
||||
}
|
||||
return content;
|
||||
}
|
||||
exports.rewriteUniModulesConsoleExpr = rewriteUniModulesConsoleExpr;
|
||||
let ts;
|
||||
function getTs() {
|
||||
if (!ts) {
|
||||
ts = (0, uts_1.resolveUTSCompiler)().getTypeScript();
|
||||
}
|
||||
return ts;
|
||||
}
|
||||
function appendUniModulesConsoleExpr(fileName, content) {
|
||||
// 仅开发模式补充console.log的at信息
|
||||
if (process.env.NODE_ENV !== 'development') {
|
||||
return content;
|
||||
}
|
||||
if (content.includes('console.')) {
|
||||
return (0, console_1.appendConsoleExpr)((0, utils_2.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, fileName.split('?')[0])), content, ts || getTs());
|
||||
}
|
||||
return content;
|
||||
}
|
||||
function createUniModulesSyncFilePreprocessor(platform, utsPlatform, isX) {
|
||||
const { preVueContext, preUVueContext } = (0, context_1.initScopedPreContext)(platform, undefined, utsPlatform, isX);
|
||||
const preContext = isX ? preUVueContext : preVueContext;
|
||||
if (!isX) {
|
||||
if (utsPlatform === 'app-android') {
|
||||
preContext.APP_ANDROID = true;
|
||||
}
|
||||
if (utsPlatform === 'app-ios') {
|
||||
preContext.APP_IOS = true;
|
||||
}
|
||||
if (utsPlatform === 'app-harmony') {
|
||||
preContext.APP_HARMONY = true;
|
||||
}
|
||||
}
|
||||
function preJs(jsCode) {
|
||||
return preprocess(jsCode, preContext, { type: 'js' });
|
||||
}
|
||||
function preHtml(htmlCode) {
|
||||
return preprocess(htmlCode, preContext, { type: 'html' });
|
||||
}
|
||||
return async (content, fileName) => {
|
||||
const extname = path_1.default.extname(fileName);
|
||||
if (extname === '.json') {
|
||||
return (0, pluginutils_1.dataToEsm)(JSON.parse(preJs(content)), {
|
||||
namedExports: true,
|
||||
preferConst: true,
|
||||
});
|
||||
}
|
||||
else if (extname === '.uts' || extname === '.ts') {
|
||||
return replaceExtApiPages(rewriteUniModulesConsoleExpr(fileName, preJs(content)));
|
||||
}
|
||||
else if (extname === '.uvue' || extname === '.vue') {
|
||||
return rewriteUniModulesConsoleExpr(fileName, preJs(preHtml(content)));
|
||||
}
|
||||
return content;
|
||||
};
|
||||
}
|
||||
function replaceExtApiPages(code) {
|
||||
// 定制实现
|
||||
if (process.env.UNI_COMPILE_EXT_API_PAGES) {
|
||||
const pages = JSON.parse(process.env.UNI_COMPILE_EXT_API_PAGES);
|
||||
Object.keys(pages).forEach((page) => {
|
||||
code = code.replaceAll(page, pages[page]);
|
||||
});
|
||||
}
|
||||
return code;
|
||||
}
|
||||
function createAppAndroidUniModulesSyncFilePreprocessorOnce(isX) {
|
||||
return isX
|
||||
? createUniXAppAndroidUniModulesSyncFilePreprocessorOnce()
|
||||
: createUniAppAndroidUniModulesSyncFilePreprocessorOnce();
|
||||
}
|
||||
exports.createAppAndroidUniModulesSyncFilePreprocessorOnce = createAppAndroidUniModulesSyncFilePreprocessorOnce;
|
||||
function createAppIosUniModulesSyncFilePreprocessorOnce(isX) {
|
||||
return isX
|
||||
? createUniXAppIosUniModulesSyncFilePreprocessorOnce()
|
||||
: createUniAppIosUniModulesSyncFilePreprocessorOnce();
|
||||
}
|
||||
exports.createAppIosUniModulesSyncFilePreprocessorOnce = createAppIosUniModulesSyncFilePreprocessorOnce;
|
||||
function createAppHarmonyUniModulesSyncFilePreprocessorOnce(isX) {
|
||||
return isX
|
||||
? createUniXAppHarmonyUniModulesSyncFilePreprocessorOnce()
|
||||
: createUniAppHarmonyUniModulesSyncFilePreprocessorOnce();
|
||||
}
|
||||
exports.createAppHarmonyUniModulesSyncFilePreprocessorOnce = createAppHarmonyUniModulesSyncFilePreprocessorOnce;
|
||||
const createUniAppAndroidUniModulesSyncFilePreprocessorOnce = (0, uni_shared_1.once)(() => {
|
||||
return createUniModulesSyncFilePreprocessor('app', 'app-android', false);
|
||||
});
|
||||
const createUniAppIosUniModulesSyncFilePreprocessorOnce = (0, uni_shared_1.once)(() => {
|
||||
return createUniModulesSyncFilePreprocessor('app', 'app-ios', false);
|
||||
});
|
||||
const createUniAppHarmonyUniModulesSyncFilePreprocessorOnce = (0, uni_shared_1.once)(() => {
|
||||
return createUniModulesSyncFilePreprocessor('app-harmony', 'app-harmony', false);
|
||||
});
|
||||
const createUniXAppAndroidUniModulesSyncFilePreprocessorOnce = (0, uni_shared_1.once)(() => {
|
||||
return createUniModulesSyncFilePreprocessor('app', 'app-android', true);
|
||||
});
|
||||
const createUniXAppIosUniModulesSyncFilePreprocessorOnce = (0, uni_shared_1.once)(() => {
|
||||
return createUniModulesSyncFilePreprocessor('app', 'app-ios', true);
|
||||
});
|
||||
const createUniXAppHarmonyUniModulesSyncFilePreprocessorOnce = (0, uni_shared_1.once)(() => {
|
||||
return createUniModulesSyncFilePreprocessor('app-harmony', 'app-harmony', true);
|
||||
});
|
||||
const utsModuleCaches = new Map();
|
||||
const utsPlugins = new Set();
|
||||
const utsProviders = new Set();
|
||||
function getCurrentCompiledUTSPlugins() {
|
||||
return utsPlugins;
|
||||
}
|
||||
exports.getCurrentCompiledUTSPlugins = getCurrentCompiledUTSPlugins;
|
||||
function getCurrentCompiledUTSProviders() {
|
||||
return utsProviders;
|
||||
}
|
||||
exports.getCurrentCompiledUTSProviders = getCurrentCompiledUTSProviders;
|
||||
let uniExtApiCompiler = async () => { };
|
||||
function emptyCacheDir(platform) {
|
||||
const uvueOutputDir = (0, uts_1.uvueOutDir)(platform);
|
||||
const tscOutputDir = (0, uts_1.tscOutDir)(platform);
|
||||
function emptyUVueDir() {
|
||||
if (fs_extra_1.default.existsSync(uvueOutputDir)) {
|
||||
(0, fs_1.emptyDir)(uvueOutputDir);
|
||||
}
|
||||
}
|
||||
emptyUVueDir();
|
||||
function emptyTscDir() {
|
||||
if (fs_extra_1.default.existsSync(tscOutputDir)) {
|
||||
(0, fs_1.emptyDir)(tscOutputDir);
|
||||
}
|
||||
}
|
||||
emptyTscDir();
|
||||
}
|
||||
const emptyKotlinCacheDirOnce = (0, uni_shared_1.once)(() => {
|
||||
emptyCacheDir('app-android');
|
||||
});
|
||||
const emptySwiftCacheDirOnce = (0, uni_shared_1.once)(() => {
|
||||
emptyCacheDir('app-ios');
|
||||
});
|
||||
const emptyHarmonyCacheDirOnce = (0, uni_shared_1.once)(() => {
|
||||
emptyCacheDir('app-harmony');
|
||||
});
|
||||
const handleCompileResult = (result, pluginContext) => {
|
||||
if (pluginContext) {
|
||||
result.deps.forEach((dep) => {
|
||||
pluginContext.addWatchFile(dep);
|
||||
});
|
||||
}
|
||||
};
|
||||
// 该插件仅限app-android、app-ios、app-harmony
|
||||
function uniUTSAppUniModulesPlugin(options = {}) {
|
||||
const isX = process.env.UNI_APP_X === 'true';
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
process.env.UNI_UTS_USING_ROLLUP = 'true';
|
||||
const uniModulesDir = (0, utils_2.normalizePath)(path_1.default.resolve(inputDir, 'uni_modules'));
|
||||
// 非 x 项目,非 HBuilderX
|
||||
if (!isX && !(0, hbx_1.isInHBuilderX)()) {
|
||||
try {
|
||||
(0, uts_1.resolveUTSCompiler)(true);
|
||||
}
|
||||
catch (e) {
|
||||
return {
|
||||
name: 'uni:uts-uni_modules-placeholder',
|
||||
apply: 'build',
|
||||
enforce: 'pre',
|
||||
resolveId(id) {
|
||||
if ((0, uts_1.isUTSProxy)(id) || (0, uts_1.isUniHelpers)(id)) {
|
||||
return id;
|
||||
}
|
||||
},
|
||||
load(id) {
|
||||
if ((0, uts_1.isUTSProxy)(id)) {
|
||||
console.error((0, utils_2.installDepTips)('devDependencies', '@dcloudio/uni-uts-v1', (0, uts_1.resolveUTSCompilerVersion)()));
|
||||
process.exit(0);
|
||||
return '';
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
const { createUniXKotlinCompilerOnce, createUniXSwiftCompilerOnce, createUniXArkTSCompilerOnce, syncUniModuleFilesByCompiler, resolveTscUniModuleIndexFileName, } = (0, uts_1.resolveUTSCompiler)();
|
||||
const uniXKotlinCompiler = process.env.UNI_APP_X_TSC === 'true' &&
|
||||
(process.env.UNI_UTS_PLATFORM === 'app-android' ||
|
||||
process.env.UNI_UTS_PLATFORM === 'app')
|
||||
? createUniXKotlinCompilerOnce()
|
||||
: null;
|
||||
const uniXSwiftCompiler = process.env.UNI_APP_X_TSC === 'true' &&
|
||||
(process.env.UNI_UTS_PLATFORM === 'app-ios' ||
|
||||
process.env.UNI_UTS_PLATFORM === 'app')
|
||||
? createUniXSwiftCompilerOnce()
|
||||
: null;
|
||||
const uniXArkTSCompiler = process.env.UNI_APP_X_TSC === 'true' &&
|
||||
process.env.UNI_UTS_PLATFORM === 'app-harmony'
|
||||
? createUniXArkTSCompilerOnce()
|
||||
: null;
|
||||
if (uniXKotlinCompiler) {
|
||||
emptyKotlinCacheDirOnce();
|
||||
(0, uts_1.genUniExtApiDeclarationFileOnce)((0, uts_1.tscOutDir)('app-android'));
|
||||
}
|
||||
if (uniXSwiftCompiler) {
|
||||
emptySwiftCacheDirOnce();
|
||||
(0, uts_1.genUniExtApiDeclarationFileOnce)((0, uts_1.tscOutDir)('app-ios'));
|
||||
}
|
||||
if (uniXArkTSCompiler) {
|
||||
emptyHarmonyCacheDirOnce();
|
||||
(0, uts_1.genUniExtApiDeclarationFileOnce)((0, uts_1.tscOutDir)('app-harmony'));
|
||||
}
|
||||
const changedFiles = new Map();
|
||||
const compilePlugin = async (pluginDir, pluginContext) => {
|
||||
const pluginId = path_1.default.basename(pluginDir);
|
||||
if (uniXKotlinCompiler) {
|
||||
const platform = 'app-android';
|
||||
await syncUniModuleFilesByCompiler(platform, uniXKotlinCompiler, pluginDir, createAppAndroidUniModulesSyncFilePreprocessorOnce(isX));
|
||||
}
|
||||
if (uniXSwiftCompiler) {
|
||||
const platform = 'app-ios';
|
||||
await syncUniModuleFilesByCompiler(platform, uniXSwiftCompiler, pluginDir, createAppIosUniModulesSyncFilePreprocessorOnce(isX));
|
||||
}
|
||||
if (uniXArkTSCompiler) {
|
||||
const platform = 'app-harmony';
|
||||
await syncUniModuleFilesByCompiler(platform, uniXArkTSCompiler, pluginDir, createAppHarmonyUniModulesSyncFilePreprocessorOnce(isX));
|
||||
}
|
||||
if (!utsPlugins.has(pluginId)) {
|
||||
utsPlugins.add(pluginId);
|
||||
if (uniXKotlinCompiler) {
|
||||
const platform = 'app-android';
|
||||
const indexFileName = resolveTscUniModuleIndexFileName(platform, pluginDir);
|
||||
if (indexFileName) {
|
||||
await uniXKotlinCompiler.addRootFile(indexFileName);
|
||||
}
|
||||
}
|
||||
if (uniXSwiftCompiler) {
|
||||
const platform = 'app-ios';
|
||||
const indexFileName = resolveTscUniModuleIndexFileName(platform, pluginDir);
|
||||
if (indexFileName) {
|
||||
await uniXSwiftCompiler.addRootFile(indexFileName);
|
||||
}
|
||||
}
|
||||
if (uniXArkTSCompiler) {
|
||||
const platform = 'app-harmony';
|
||||
const indexFileName = resolveTscUniModuleIndexFileName(platform, pluginDir);
|
||||
if (indexFileName) {
|
||||
await uniXArkTSCompiler.addRootFile(indexFileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 处理uni_modules中的文件变更
|
||||
const files = changedFiles.get(pluginId);
|
||||
if (files) {
|
||||
// 仅限watch模式是会生效
|
||||
changedFiles.delete(pluginId);
|
||||
if (uniXKotlinCompiler) {
|
||||
await uniXKotlinCompiler.invalidate(files);
|
||||
}
|
||||
if (uniXSwiftCompiler) {
|
||||
await uniXSwiftCompiler.invalidate(files);
|
||||
}
|
||||
if (uniXArkTSCompiler) {
|
||||
await uniXArkTSCompiler.invalidate(files);
|
||||
}
|
||||
}
|
||||
const pkgJson = require(path_1.default.join(pluginDir, 'package.json'));
|
||||
const isExtApi = !!pkgJson.uni_modules?.['uni-ext-api'];
|
||||
const extApiProvider = resolveExtApiProvider(pkgJson);
|
||||
// 如果是 provider 扩展,需要判断 provider 的宿主插件是否在本地,在的话,自动导入该宿主插件包名
|
||||
let uniExtApiProviderServicePlugin = '';
|
||||
if (extApiProvider?.servicePlugin) {
|
||||
if (fs_extra_1.default.existsSync(path_1.default.resolve(inputDir, 'uni_modules', extApiProvider.servicePlugin))) {
|
||||
uniExtApiProviderServicePlugin = extApiProvider.servicePlugin;
|
||||
}
|
||||
}
|
||||
const compiler = (0, uts_1.resolveUTSCompiler)();
|
||||
// 处理依赖的 uts 插件
|
||||
// TODO 当本地有ext-api时,也应该自动加入deps,不然uts内部使用了该api,也会导致编译失败
|
||||
const deps =
|
||||
// 框架内部编译不需要处理依赖
|
||||
process.env.UNI_COMPILE_TARGET === 'ext-api'
|
||||
? []
|
||||
: (0, uni_modules_1.parseUTSModuleDeps)(pkgJson.uni_modules?.dependencies || [], inputDir);
|
||||
if (deps.length) {
|
||||
for (const dep of deps) {
|
||||
if (dep) {
|
||||
const depPluginDir = (0, utils_2.normalizePath)(path_1.default.resolve(uniModulesDir, dep));
|
||||
// 本次编译流程中已编译过该插件,直接使用缓存
|
||||
if (utsModuleCaches.get(depPluginDir)) {
|
||||
await utsModuleCaches.get(depPluginDir)().then((result) => {
|
||||
if (result) {
|
||||
handleCompileResult(result, pluginContext);
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
const compile = (0, uni_shared_1.once)(() => {
|
||||
return compilePlugin(depPluginDir, pluginContext);
|
||||
});
|
||||
utsModuleCaches.set(depPluginDir, compile);
|
||||
await compile().then((result) => {
|
||||
if (result) {
|
||||
handleCompileResult(result, pluginContext);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (process.env.UNI_PLATFORM === 'app-harmony') {
|
||||
return compiler.compileArkTS(pluginDir, {
|
||||
isX: !!options.x,
|
||||
isExtApi,
|
||||
sourceMap: (0, utils_2.enableSourceMap)(),
|
||||
rewriteConsoleExpr: appendUniModulesConsoleExpr,
|
||||
uni_modules: deps,
|
||||
transform: {
|
||||
uniExtApiProviderName: extApiProvider?.name,
|
||||
uniExtApiProviderService: extApiProvider?.service,
|
||||
uniExtApiProviderServicePlugin,
|
||||
},
|
||||
});
|
||||
}
|
||||
function filterAutoImports(autoImports, source) {
|
||||
if (autoImports[source]) {
|
||||
// 移除 source
|
||||
return Object.keys(autoImports).reduce((imports, key) => {
|
||||
if (key !== source) {
|
||||
imports[key] = autoImports[key];
|
||||
}
|
||||
return imports;
|
||||
}, {});
|
||||
}
|
||||
return autoImports;
|
||||
}
|
||||
return compiler.compile(pluginDir, {
|
||||
isX: !!options.x,
|
||||
isSingleThread: !!options.isSingleThread,
|
||||
isPlugin: true,
|
||||
isExtApi,
|
||||
extApis: options.extApis,
|
||||
sourceMap: (0, utils_2.enableSourceMap)(),
|
||||
uni_modules: deps,
|
||||
rewriteConsoleExpr: appendUniModulesConsoleExpr,
|
||||
transform: {
|
||||
uniExtApiProviderName: extApiProvider?.name,
|
||||
uniExtApiProviderService: extApiProvider?.service,
|
||||
uniExtApiProviderServicePlugin,
|
||||
},
|
||||
async kotlinAutoImports() {
|
||||
return (0, uts_1.initUTSKotlinAutoImportsOnce)().then((autoImports) => {
|
||||
return filterAutoImports(autoImports, (0, uts_1.parseKotlinPackageWithPluginId)(pluginId, true));
|
||||
});
|
||||
},
|
||||
async swiftAutoImports() {
|
||||
return (0, uts_1.initUTSSwiftAutoImportsOnce)().then((autoImports) => {
|
||||
return filterAutoImports(autoImports, (0, uts_1.parseSwiftPackageWithPluginId)(pluginId, true));
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
uniExtApiCompiler = async () => {
|
||||
// 此方法为兜底方法,确保uni_modules中的所有插件都会编译,目前仅用于编译provider
|
||||
// 获取 provider 扩展(编译所有uni)
|
||||
const plugins = (0, uni_modules_1.getUniExtApiPlugins)().filter((provider) => !utsPlugins.has(provider.plugin));
|
||||
for (const plugin of plugins) {
|
||||
const pluginDir = path_1.default.resolve(inputDir, 'uni_modules', plugin.plugin);
|
||||
// 如果是 app-js 环境
|
||||
if (process.env.UNI_APP_X_UVUE_SCRIPT_ENGINE === 'js') {
|
||||
if (fs_extra_1.default.existsSync(path_1.default.resolve(pluginDir, 'utssdk', 'app-js', 'index.uts'))) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (process.env.UNI_PLATFORM === 'app-harmony') {
|
||||
// uniExtApiCompiler本身是为X项目准备的,但是在app-harmony项目中也会调用
|
||||
// uni-app-x app-harmony暂不支持其他类型插件
|
||||
if (!fs_extra_1.default.existsSync(path_1.default.resolve(pluginDir, 'utssdk', 'app-harmony', 'index.uts'))) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
utsProviders.add(plugin.plugin);
|
||||
const result = await compilePlugin(pluginDir);
|
||||
if (result) {
|
||||
// 时机不对,不能addWatch
|
||||
// result.deps.forEach((dep) => {
|
||||
// this.addWatchFile(dep)
|
||||
// })
|
||||
}
|
||||
}
|
||||
};
|
||||
return {
|
||||
name: 'uni:uts-uni_modules',
|
||||
apply: 'build',
|
||||
enforce: 'pre',
|
||||
async configResolved() {
|
||||
if (uniXKotlinCompiler) {
|
||||
await uniXKotlinCompiler.init();
|
||||
}
|
||||
if (uniXSwiftCompiler) {
|
||||
await uniXSwiftCompiler.init();
|
||||
}
|
||||
if (uniXArkTSCompiler) {
|
||||
await uniXArkTSCompiler.init();
|
||||
}
|
||||
},
|
||||
resolveId(id, importer) {
|
||||
if ((0, uts_1.isUTSProxy)(id) || (0, uts_1.isUniHelpers)(id)) {
|
||||
return id;
|
||||
}
|
||||
// 加密插件缓存目录的css文件
|
||||
if (id.endsWith('.css')) {
|
||||
return;
|
||||
}
|
||||
const module = (0, uts_1.resolveUTSAppModule)(process.env.UNI_UTS_PLATFORM, id, importer ? path_1.default.dirname(importer) : inputDir, options.x !== true);
|
||||
if (module) {
|
||||
// app-js 会直接返回 index.uts 路径,不需要 uts-proxy
|
||||
if (module.endsWith('.uts')) {
|
||||
return module;
|
||||
}
|
||||
// prefix the polyfill id with \0 to tell other plugins not to try to load or transform it
|
||||
return module + '?uts-proxy';
|
||||
}
|
||||
},
|
||||
load(id) {
|
||||
if ((0, uts_1.isUTSProxy)(id)) {
|
||||
return '';
|
||||
}
|
||||
},
|
||||
async buildEnd() {
|
||||
utsModuleCaches.clear();
|
||||
changedFiles.clear();
|
||||
if (process.env.NODE_ENV !== 'development' || !(0, utils_2.isNormalCompileTarget)()) {
|
||||
if (uniXKotlinCompiler) {
|
||||
await uniXKotlinCompiler.close();
|
||||
}
|
||||
if (uniXSwiftCompiler) {
|
||||
await uniXSwiftCompiler.close();
|
||||
}
|
||||
if (uniXArkTSCompiler) {
|
||||
await uniXArkTSCompiler.close();
|
||||
}
|
||||
}
|
||||
},
|
||||
watchChange(fileName, change) {
|
||||
if (uniXKotlinCompiler || uniXSwiftCompiler || uniXArkTSCompiler) {
|
||||
fileName = (0, utils_2.normalizePath)(fileName);
|
||||
if (fileName.startsWith(uniModulesDir)) {
|
||||
// 仅处理uni_modules中的文件
|
||||
const plugin = fileName.slice(uniModulesDir.length + 1).split('/')[0];
|
||||
if (utsPlugins.has(plugin)) {
|
||||
const changeFile = { fileName, event: change.event };
|
||||
if (!changedFiles.has(plugin)) {
|
||||
changedFiles.set(plugin, [changeFile]);
|
||||
}
|
||||
else {
|
||||
changedFiles.get(plugin).push(changeFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
async transform(_, id, opts) {
|
||||
if (opts && opts.ssr) {
|
||||
return;
|
||||
}
|
||||
if (!(0, uts_1.isUTSProxy)(id)) {
|
||||
return;
|
||||
}
|
||||
const { filename } = (0, utils_1.parseVueRequest)(id.replace('\0', ''));
|
||||
// 当 vue 和 nvue 均引用了相同 uts 插件,解决两套编译器会编译两次 uts 插件的问题
|
||||
// 通过缓存,保证同一个 uts 插件只编译一次
|
||||
const pluginDir = (0, utils_2.normalizePath)(filename);
|
||||
if (utsModuleCaches.get(pluginDir)) {
|
||||
return utsModuleCaches.get(pluginDir)().then((result) => {
|
||||
if (result) {
|
||||
result.deps.forEach((dep) => {
|
||||
this.addWatchFile(dep);
|
||||
});
|
||||
return {
|
||||
code: result.code,
|
||||
map: null,
|
||||
syntheticNamedExports: result.encrypt,
|
||||
meta: result.meta,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
const compile = (0, uni_shared_1.once)(() => {
|
||||
return compilePlugin(pluginDir, this);
|
||||
});
|
||||
utsModuleCaches.set(pluginDir, compile);
|
||||
const result = await compile();
|
||||
if (result) {
|
||||
result.deps.forEach((dep) => {
|
||||
this.addWatchFile(dep);
|
||||
});
|
||||
return {
|
||||
code: result.code,
|
||||
map: null,
|
||||
syntheticNamedExports: result.encrypt,
|
||||
meta: result.meta,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniUTSAppUniModulesPlugin = uniUTSAppUniModulesPlugin;
|
||||
async function buildUniExtApis() {
|
||||
await uniExtApiCompiler();
|
||||
}
|
||||
exports.buildUniExtApis = buildUniExtApis;
|
||||
function resolveExtApiProvider(pkg) {
|
||||
const provider = pkg.uni_modules?.['uni-ext-api']?.provider;
|
||||
if (provider?.service) {
|
||||
if (provider.name && !provider.servicePlugin) {
|
||||
provider.servicePlugin = 'uni-' + provider.service;
|
||||
}
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
exports.resolveExtApiProvider = resolveExtApiProvider;
|
||||
function uniDecryptUniModulesPlugin() {
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
const isX = process.env.UNI_APP_X === 'true';
|
||||
return {
|
||||
name: 'uni:uni_modules-d',
|
||||
enforce: 'pre',
|
||||
async configResolved() {
|
||||
if (isX && (0, utils_2.isNormalCompileTarget)()) {
|
||||
const manifest = (0, json_1.parseManifestJsonOnce)(inputDir);
|
||||
await (0, uni_modules_cloud_1.checkEncryptUniModules)(inputDir, {
|
||||
mode: process.env.NODE_ENV !== 'development'
|
||||
? 'production'
|
||||
: 'development',
|
||||
packType: process.env.UNI_APP_PACK_TYPE ||
|
||||
(process.env.NODE_ENV !== 'development' ? 'release' : 'debug'),
|
||||
compilerVersion: process.env.UNI_COMPILER_VERSION,
|
||||
appid: manifest.appid,
|
||||
appname: manifest.name,
|
||||
platform: process.env.UNI_UTS_PLATFORM,
|
||||
'uni-app-x': isX,
|
||||
});
|
||||
}
|
||||
},
|
||||
resolveId(id) {
|
||||
if ((0, uts_1.isUTSProxy)(id) || (0, uts_1.isUniHelpers)(id)) {
|
||||
return id;
|
||||
}
|
||||
if (isX && (0, utils_2.isNormalCompileTarget)() && !id.endsWith('.css')) {
|
||||
const resolvedId = (0, uni_modules_cloud_1.resolveEncryptUniModule)(id, process.env.UNI_UTS_PLATFORM, process.env.UNI_APP_X === 'true');
|
||||
if (resolvedId) {
|
||||
return resolvedId;
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniDecryptUniModulesPlugin = uniDecryptUniModulesPlugin;
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniUTSUVueJavaScriptPlugin(options?: {}): Plugin;
|
||||
/**
|
||||
* 将 <script> 标签中的 lang="uts" 替换为 lang="ts"
|
||||
* 主要是当前功能内部使用 x.vite.config.ts 配置
|
||||
* @param options
|
||||
* @returns
|
||||
*/
|
||||
export declare function uniUVueTypeScriptPlugin(options?: {}): Plugin;
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniUVueTypeScriptPlugin = exports.uniUTSUVueJavaScriptPlugin = void 0;
|
||||
const vue_1 = require("../../../vue");
|
||||
function uniUTSUVueJavaScriptPlugin(options = {}) {
|
||||
process.env.UNI_UTS_USING_ROLLUP = 'true';
|
||||
return {
|
||||
name: 'uni:uts-uvue',
|
||||
enforce: 'pre',
|
||||
configResolved(config) {
|
||||
// 移除自带的 esbuild 处理 ts 文件
|
||||
const index = config.plugins.findIndex((p) => p.name === 'vite:esbuild');
|
||||
if (index > -1) {
|
||||
// @ts-expect-error
|
||||
config.plugins.splice(index, 1);
|
||||
}
|
||||
},
|
||||
transform(code, id) {
|
||||
if (!(0, vue_1.isVueSfcFile)(id)) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
code: code.replace(/<script([^>]*)>/gi, (match, attributes) => {
|
||||
// 如果 <script> 标签中没有 lang 属性,添加 lang="uts"
|
||||
if (!/lang=["']?[^"']*["']?/.test(attributes)) {
|
||||
return `<script${attributes} lang="uts">`;
|
||||
}
|
||||
// 否则,将现有的 lang 属性替换为 lang="uts"
|
||||
return match.replace(/lang=["']?ts["']?/, 'lang="uts"');
|
||||
}),
|
||||
map: { mappings: '' },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniUTSUVueJavaScriptPlugin = uniUTSUVueJavaScriptPlugin;
|
||||
/**
|
||||
* 将 <script> 标签中的 lang="uts" 替换为 lang="ts"
|
||||
* 主要是当前功能内部使用 x.vite.config.ts 配置
|
||||
* @param options
|
||||
* @returns
|
||||
*/
|
||||
function uniUVueTypeScriptPlugin(options = {}) {
|
||||
return {
|
||||
name: 'uni:uvue-ts',
|
||||
enforce: 'pre',
|
||||
transform(code, id) {
|
||||
if (!(0, vue_1.isVueSfcFile)(id)) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
code: code.replace(/<script([^>]*)>/gi, (match, attributes) => {
|
||||
// 如果 <script> 标签中没有 lang 属性,添加 lang="uts"
|
||||
if (!/lang=["']?[^"']*["']?/.test(attributes)) {
|
||||
return `<script${attributes} lang="ts">`;
|
||||
}
|
||||
// 否则,将现有的 lang 属性替换为 lang="uts"
|
||||
return match.replace(/lang=["']?uts["']?/, 'lang="ts"');
|
||||
}),
|
||||
map: { mappings: '' },
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniUVueTypeScriptPlugin = uniUVueTypeScriptPlugin;
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export declare function emptyCssComments(raw: string): string;
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.emptyCssComments = void 0;
|
||||
const utils_1 = require("./utils");
|
||||
const blankReplacer = (s) => ' '.repeat(s.length);
|
||||
function emptyCssComments(raw) {
|
||||
return raw.replace(utils_1.multilineCommentsRE, blankReplacer);
|
||||
}
|
||||
exports.emptyCssComments = emptyCssComments;
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export type { ResolvedConfig } from 'vite';
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
Generated
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts
|
||||
*/
|
||||
/**
|
||||
* Prefix for resolved fs paths, since windows paths may not be valid as URLs.
|
||||
*/
|
||||
export declare const FS_PREFIX = "/@fs/";
|
||||
export declare const CLIENT_PUBLIC_PATH = "/@vite/client";
|
||||
Generated
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.CLIENT_PUBLIC_PATH = exports.FS_PREFIX = void 0;
|
||||
/**
|
||||
* https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts
|
||||
*/
|
||||
/**
|
||||
* Prefix for resolved fs paths, since windows paths may not be valid as URLs.
|
||||
*/
|
||||
exports.FS_PREFIX = `/@fs/`;
|
||||
exports.CLIENT_PUBLIC_PATH = `/@vite/client`;
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export type { ResolveFn, ViteDevServer } from 'vite';
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export type { Plugin } from 'vite';
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
Generated
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
/// <reference types="node" />
|
||||
import type { OutputOptions, PluginContext, RenderedChunk } from 'rollup';
|
||||
import type { Plugin } from '../plugin';
|
||||
import type { ResolvedConfig } from '../config';
|
||||
export declare const assetUrlRE: RegExp;
|
||||
export declare const chunkToEmittedAssetsMap: WeakMap<RenderedChunk, Set<string>>;
|
||||
/**
|
||||
* Also supports loading plain strings with import text from './foo.txt?raw'
|
||||
*/
|
||||
export declare function assetPlugin(config: ResolvedConfig, options?: {
|
||||
isAndroidX?: boolean;
|
||||
}): Plugin;
|
||||
export declare function parseAssets(config: ResolvedConfig, code: string): string;
|
||||
export declare function registerAssetToChunk(chunk: RenderedChunk, file: string): void;
|
||||
export declare function checkPublicFile(url: string, { publicDir }: ResolvedConfig): string | undefined;
|
||||
export declare function fileToUrl(id: string, config: ResolvedConfig, ctx: PluginContext, canInline: boolean | undefined, isStaticFile: (file: string) => boolean): string;
|
||||
export declare function getAssetFilename(hash: string, config: ResolvedConfig): string | undefined;
|
||||
/**
|
||||
* converts the source filepath of the asset to the output filename based on the assetFileNames option. \
|
||||
* this function imitates the behavior of rollup.js. \
|
||||
* https://rollupjs.org/guide/en/#outputassetfilenames
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const content = Buffer.from('text');
|
||||
* const fileName = assetFileNamesToFileName(
|
||||
* 'assets/[name].[hash][extname]',
|
||||
* '/path/to/file.txt',
|
||||
* getAssetHash(content),
|
||||
* content
|
||||
* )
|
||||
* // fileName: 'assets/file.982d9e3e.txt'
|
||||
* ```
|
||||
*
|
||||
* @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
|
||||
* @param file filepath of the asset
|
||||
* @param contentHash hash of the asset. used for `'[hash]'` placeholder
|
||||
* @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
|
||||
* @returns output filename
|
||||
*/
|
||||
export declare function assetFileNamesToFileName(assetFileNames: Exclude<OutputOptions['assetFileNames'], undefined>, file: string, contentHash: string, content: string | Buffer): string;
|
||||
export declare function getAssetHash(content: Buffer | string): string;
|
||||
export declare function urlToBuiltUrl(url: string, importer: string, config: ResolvedConfig, pluginContext: PluginContext, isStaticFile: (file: string) => boolean): string;
|
||||
Generated
Vendored
+340
@@ -0,0 +1,340 @@
|
||||
"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.urlToBuiltUrl = exports.getAssetHash = exports.assetFileNamesToFileName = exports.getAssetFilename = exports.fileToUrl = exports.checkPublicFile = exports.registerAssetToChunk = exports.parseAssets = exports.assetPlugin = exports.chunkToEmittedAssetsMap = exports.assetUrlRE = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const url_1 = require("url");
|
||||
const lite_1 = __importDefault(require("mime/lite"));
|
||||
const fs_extra_1 = __importStar(require("fs-extra"));
|
||||
const magic_string_1 = __importDefault(require("magic-string"));
|
||||
const crypto_1 = require("crypto");
|
||||
const shared_1 = require("@vue/shared");
|
||||
const utils_1 = require("../utils");
|
||||
const utils_2 = require("../../../../vite/utils/utils");
|
||||
const utils_3 = require("../../../../utils");
|
||||
const static_1 = require("./static");
|
||||
exports.assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g;
|
||||
const rawRE = /(\?|&)raw(?:&|$)/;
|
||||
const urlRE = /(\?|&)url(?:&|$)/;
|
||||
exports.chunkToEmittedAssetsMap = new WeakMap();
|
||||
const assetCache = new WeakMap();
|
||||
const assetHashToFilenameMap = new WeakMap();
|
||||
// save hashes of the files that has been emitted in build watch
|
||||
const emittedHashMap = new WeakMap();
|
||||
/**
|
||||
* Also supports loading plain strings with import text from './foo.txt?raw'
|
||||
*/
|
||||
function assetPlugin(config, options) {
|
||||
// assetHashToFilenameMap initialization in buildStart causes getAssetFilename to return undefined
|
||||
assetHashToFilenameMap.set(config, new Map());
|
||||
return {
|
||||
name: 'vite:asset',
|
||||
buildStart() {
|
||||
assetCache.set(config, [new Map(), new Map()]);
|
||||
emittedHashMap.set(config, new Set());
|
||||
},
|
||||
resolveId(id) {
|
||||
if (!config.assetsInclude((0, utils_1.cleanUrl)(id))) {
|
||||
return;
|
||||
}
|
||||
// imports to absolute urls pointing to files in /public
|
||||
// will fail to resolve in the main resolver. handle them here.
|
||||
const publicFile = checkPublicFile(id, config);
|
||||
if (publicFile) {
|
||||
return id;
|
||||
}
|
||||
},
|
||||
async load(id) {
|
||||
if (id.startsWith('\0')) {
|
||||
// Rollup convention, this id should be handled by the
|
||||
// plugin that marked it with \0
|
||||
return;
|
||||
}
|
||||
// raw requests, read from disk
|
||||
if (rawRE.test(id)) {
|
||||
const file = checkPublicFile(id, config) || (0, utils_1.cleanUrl)(id);
|
||||
// raw query, read file and return as string
|
||||
return `export default ${JSON.stringify(await fs_extra_1.promises.readFile(file, 'utf-8'))}`;
|
||||
}
|
||||
if (!config.assetsInclude((0, utils_1.cleanUrl)(id)) && !urlRE.test(id)) {
|
||||
return;
|
||||
}
|
||||
id = id.replace(urlRE, '$1').replace(/[\?&]$/, '');
|
||||
const url = await fileToUrl(id, config, options?.isAndroidX
|
||||
? {
|
||||
emitFile(emittedFile) {
|
||||
// 直接写入目标目录
|
||||
fs_extra_1.default.outputFileSync(path_1.default.resolve(process.env.UNI_OUTPUT_DIR, emittedFile.fileName), emittedFile.source);
|
||||
},
|
||||
}
|
||||
: this, false, (0, static_1.getIsStaticFile)());
|
||||
if (options?.isAndroidX) {
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: (0, utils_3.normalizeEmitAssetFileName)((0, utils_3.normalizeNodeModules)(path_1.default.relative(process.env.UNI_INPUT_DIR, id))),
|
||||
source: `export default ${JSON.stringify(parseAssets(config, url))}`,
|
||||
});
|
||||
}
|
||||
return `export default ${JSON.stringify(url)}`;
|
||||
},
|
||||
renderChunk(code, chunk) {
|
||||
let match;
|
||||
let s;
|
||||
exports.assetUrlRE.lastIndex = 0;
|
||||
// Urls added with JS using e.g.
|
||||
// imgElement.src = "__VITE_ASSET__5aa0ddc0__" are using quotes
|
||||
// Urls added in CSS that is imported in JS end up like
|
||||
// var inlined = ".inlined{color:green;background:url(__VITE_ASSET__5aa0ddc0__)}\n";
|
||||
// In both cases, the wrapping should already be fine
|
||||
while ((match = exports.assetUrlRE.exec(code))) {
|
||||
s = s || (s = new magic_string_1.default(code));
|
||||
const [full, hash, postfix = ''] = match;
|
||||
// some internal plugins may still need to emit chunks (e.g. worker) so
|
||||
// fallback to this.getFileName for that.
|
||||
const file = getAssetFilename(hash, config) || this.getFileName(hash);
|
||||
registerAssetToChunk(chunk, file);
|
||||
const outputFilepath = config.base + file + postfix;
|
||||
s.overwrite(match.index, match.index + full.length, outputFilepath);
|
||||
}
|
||||
if (s) {
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: (0, utils_2.withSourcemap)(config) ? s.generateMap({ hires: true }) : null,
|
||||
};
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.assetPlugin = assetPlugin;
|
||||
function parseAssets(config, code) {
|
||||
let match;
|
||||
let s;
|
||||
exports.assetUrlRE.lastIndex = 0;
|
||||
while ((match = exports.assetUrlRE.exec(code))) {
|
||||
s = s || (s = new magic_string_1.default(code));
|
||||
const [full, hash, postfix = ''] = match;
|
||||
// some internal plugins may still need to emit chunks (e.g. worker) so
|
||||
// fallback to this.getFileName for that.
|
||||
const file = getAssetFilename(hash, config);
|
||||
const outputFilepath = config.base + file + postfix;
|
||||
s.overwrite(match.index, match.index + full.length, outputFilepath);
|
||||
}
|
||||
if (s) {
|
||||
return s.toString();
|
||||
}
|
||||
return code;
|
||||
}
|
||||
exports.parseAssets = parseAssets;
|
||||
function registerAssetToChunk(chunk, file) {
|
||||
let emitted = exports.chunkToEmittedAssetsMap.get(chunk);
|
||||
if (!emitted) {
|
||||
emitted = new Set();
|
||||
exports.chunkToEmittedAssetsMap.set(chunk, emitted);
|
||||
}
|
||||
emitted.add((0, utils_1.cleanUrl)(file));
|
||||
}
|
||||
exports.registerAssetToChunk = registerAssetToChunk;
|
||||
function checkPublicFile(url, { publicDir }) {
|
||||
// note if the file is in /public, the resolver would have returned it
|
||||
// as-is so it's not going to be a fully resolved path.
|
||||
if (!publicDir || !url.startsWith('/')) {
|
||||
return;
|
||||
}
|
||||
const publicFile = path_1.default.join(publicDir, (0, utils_1.cleanUrl)(url));
|
||||
if (fs_extra_1.default.existsSync(publicFile)) {
|
||||
return publicFile;
|
||||
}
|
||||
else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
exports.checkPublicFile = checkPublicFile;
|
||||
function fileToUrl(id, config, ctx, canInline = false, isStaticFile) {
|
||||
return fileToBuiltUrl(id, config, ctx, false, canInline, isStaticFile);
|
||||
}
|
||||
exports.fileToUrl = fileToUrl;
|
||||
function getAssetFilename(hash, config) {
|
||||
return assetHashToFilenameMap.get(config)?.get(hash);
|
||||
}
|
||||
exports.getAssetFilename = getAssetFilename;
|
||||
/**
|
||||
* converts the source filepath of the asset to the output filename based on the assetFileNames option. \
|
||||
* this function imitates the behavior of rollup.js. \
|
||||
* https://rollupjs.org/guide/en/#outputassetfilenames
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const content = Buffer.from('text');
|
||||
* const fileName = assetFileNamesToFileName(
|
||||
* 'assets/[name].[hash][extname]',
|
||||
* '/path/to/file.txt',
|
||||
* getAssetHash(content),
|
||||
* content
|
||||
* )
|
||||
* // fileName: 'assets/file.982d9e3e.txt'
|
||||
* ```
|
||||
*
|
||||
* @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'`
|
||||
* @param file filepath of the asset
|
||||
* @param contentHash hash of the asset. used for `'[hash]'` placeholder
|
||||
* @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function
|
||||
* @returns output filename
|
||||
*/
|
||||
function assetFileNamesToFileName(assetFileNames, file, contentHash, content) {
|
||||
const basename = path_1.default.basename(file);
|
||||
// placeholders for `assetFileNames`
|
||||
// `hash` is slightly different from the rollup's one
|
||||
const extname = path_1.default.extname(basename);
|
||||
const ext = extname.substring(1);
|
||||
const name = basename.slice(0, -extname.length);
|
||||
const hash = contentHash;
|
||||
if ((0, shared_1.isFunction)(assetFileNames)) {
|
||||
assetFileNames = assetFileNames({
|
||||
name: file,
|
||||
originalFileName: null,
|
||||
source: content,
|
||||
type: 'asset',
|
||||
});
|
||||
if (!(0, shared_1.isString)(assetFileNames)) {
|
||||
throw new TypeError('assetFileNames must return a string');
|
||||
}
|
||||
}
|
||||
else if (!(0, shared_1.isString)(assetFileNames)) {
|
||||
throw new TypeError('assetFileNames must be a string or a function');
|
||||
}
|
||||
const fileName = assetFileNames.replace(/\[\w+\]/g, (placeholder) => {
|
||||
switch (placeholder) {
|
||||
case '[ext]':
|
||||
return ext;
|
||||
case '[extname]':
|
||||
return extname;
|
||||
case '[hash]':
|
||||
return hash;
|
||||
case '[name]':
|
||||
return sanitizeFileName(name);
|
||||
}
|
||||
throw new Error(`invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"`);
|
||||
});
|
||||
return fileName;
|
||||
}
|
||||
exports.assetFileNamesToFileName = assetFileNamesToFileName;
|
||||
// taken from https://github.com/rollup/rollup/blob/a8647dac0fe46c86183be8596ef7de25bc5b4e4b/src/utils/sanitizeFileName.ts
|
||||
// https://datatracker.ietf.org/doc/html/rfc2396
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
|
||||
const DRIVE_LETTER_REGEX = /^[a-z]:/i;
|
||||
function sanitizeFileName(name) {
|
||||
const match = DRIVE_LETTER_REGEX.exec(name);
|
||||
const driveLetter = match ? match[0] : '';
|
||||
// A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
|
||||
// Otherwise, avoid them because they can refer to NTFS alternate data streams.
|
||||
return (driveLetter +
|
||||
name.substring(driveLetter.length).replace(INVALID_CHAR_REGEX, '_'));
|
||||
}
|
||||
/**
|
||||
* Register an asset to be emitted as part of the bundle (if necessary)
|
||||
* and returns the resolved public URL
|
||||
*/
|
||||
function fileToBuiltUrl(id, config, pluginContext, skipPublicCheck = false, canInline = false, isStaticFile) {
|
||||
if (!skipPublicCheck && checkPublicFile(id, config)) {
|
||||
return config.base + id.slice(1);
|
||||
}
|
||||
const [cacheForUrl, cacheForBase64] = assetCache.get(config);
|
||||
const cache = canInline ? cacheForBase64 : cacheForUrl;
|
||||
const cached = cache.get(id);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
const file = (0, utils_1.cleanUrl)(id);
|
||||
const content = fs_extra_1.default.readFileSync(file);
|
||||
let url;
|
||||
if (canInline && content.length < Number(config.build.assetsInlineLimit)) {
|
||||
// base64 inlined as a string
|
||||
url = `data:${lite_1.default.getType(file)};base64,${content.toString('base64')}`;
|
||||
}
|
||||
else {
|
||||
const map = assetHashToFilenameMap.get(config);
|
||||
const contentHash = getAssetHash(content);
|
||||
const { search, hash } = (0, url_1.parse)(id);
|
||||
const postfix = (search || '') + (hash || '');
|
||||
const output = config.build?.rollupOptions?.output;
|
||||
const defaultAssetFileNames = path_1.default.posix.join(config.build.assetsDir, '[name].[hash][extname]');
|
||||
// Steps to determine which assetFileNames will be actually used.
|
||||
// First, if output is an object or string, use assetFileNames in it.
|
||||
// And a default assetFileNames as fallback.
|
||||
let assetFileNames = (output && !Array.isArray(output) ? output.assetFileNames : undefined) ??
|
||||
defaultAssetFileNames;
|
||||
if (output && Array.isArray(output)) {
|
||||
// Second, if output is an array, adopt assetFileNames in the first object.
|
||||
assetFileNames = output[0].assetFileNames ?? assetFileNames;
|
||||
}
|
||||
const inputDir = (0, utils_1.normalizePath)(process.env.UNI_INPUT_DIR);
|
||||
const isStatic = isStaticFile(file);
|
||||
let fileName = file.startsWith(inputDir) && isStatic
|
||||
? // 需要处理 HBuilderX 项目中的 node_modules 目录
|
||||
(0, utils_3.normalizeNodeModules)(path_1.default.posix.relative(inputDir, file))
|
||||
: assetFileNamesToFileName(assetFileNames, file, contentHash, content);
|
||||
if (!map.has(contentHash)) {
|
||||
map.set(contentHash, fileName);
|
||||
}
|
||||
if (!isStatic) {
|
||||
const emittedSet = emittedHashMap.get(config);
|
||||
if (!emittedSet.has(contentHash)) {
|
||||
pluginContext.emitFile({
|
||||
name: fileName,
|
||||
fileName,
|
||||
type: 'asset',
|
||||
source: content,
|
||||
});
|
||||
emittedSet.add(contentHash);
|
||||
}
|
||||
}
|
||||
url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`;
|
||||
}
|
||||
cache.set(id, url);
|
||||
return url;
|
||||
}
|
||||
function getAssetHash(content) {
|
||||
return (0, crypto_1.createHash)('sha256').update(content).digest('hex').slice(0, 8);
|
||||
}
|
||||
exports.getAssetHash = getAssetHash;
|
||||
function urlToBuiltUrl(url, importer, config, pluginContext, isStaticFile) {
|
||||
if (checkPublicFile(url, config)) {
|
||||
return config.base + url.slice(1);
|
||||
}
|
||||
const file = url.startsWith('/')
|
||||
? path_1.default.join(config.root, url)
|
||||
: path_1.default.join(path_1.default.dirname(importer), url);
|
||||
return fileToBuiltUrl(file, config, pluginContext,
|
||||
// skip public check since we just did it above
|
||||
true, false, isStaticFile);
|
||||
}
|
||||
exports.urlToBuiltUrl = urlToBuiltUrl;
|
||||
Generated
Vendored
+71
@@ -0,0 +1,71 @@
|
||||
import type { SFCDescriptor } from '@vue/compiler-sfc';
|
||||
import type { ExistingRawSourceMap, RollupError } from 'rollup';
|
||||
import type * as PostCSS from 'postcss';
|
||||
import type { Plugin } from '../plugin';
|
||||
import type { ResolvedConfig } from '../config';
|
||||
import type { ResolveFn } from '../';
|
||||
import * as Postcss from 'postcss';
|
||||
export interface CSSOptions {
|
||||
/**
|
||||
* https://github.com/css-modules/postcss-modules
|
||||
*/
|
||||
modules?: CSSModulesOptions | false;
|
||||
preprocessorOptions?: Record<string, any>;
|
||||
postcss?: string | (Postcss.ProcessOptions & {
|
||||
plugins?: Postcss.Plugin[];
|
||||
});
|
||||
}
|
||||
export interface CSSModulesOptions {
|
||||
getJSON?: (cssFileName: string, json: Record<string, string>, outputFileName: string) => void;
|
||||
scopeBehaviour?: 'global' | 'local';
|
||||
globalModulePaths?: RegExp[];
|
||||
generateScopedName?: string | ((name: string, filename: string, css: string) => string);
|
||||
hashPrefix?: string;
|
||||
/**
|
||||
* default: null
|
||||
*/
|
||||
localsConvention?: 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | null;
|
||||
}
|
||||
export declare const cssLangRE: RegExp;
|
||||
export declare const commonjsProxyRE: RegExp;
|
||||
export declare const isCSSRequest: (request: string) => boolean;
|
||||
export declare const isDirectCSSRequest: (request: string) => boolean;
|
||||
export declare function getCssDepMap(): Map<string, Set<string>>;
|
||||
/**
|
||||
* Plugin applied before user plugins
|
||||
*/
|
||||
export declare function cssPlugin(config: ResolvedConfig, options?: {
|
||||
isAndroidX: boolean;
|
||||
getDescriptor?(filename: string): SFCDescriptor | undefined;
|
||||
createUrlReplacer?: (resolve: ResolveFn) => CssUrlReplacer;
|
||||
}): Plugin;
|
||||
/**
|
||||
* Plugin applied after user plugins
|
||||
*/
|
||||
export declare function cssPostPlugin(config: ResolvedConfig, { platform, isJsCode, preserveModules, chunkCssFilename, chunkCssCode, includeComponentCss, }: {
|
||||
platform: UniApp.PLATFORM;
|
||||
isJsCode?: boolean;
|
||||
preserveModules?: boolean;
|
||||
chunkCssFilename: (id: string) => string | void;
|
||||
chunkCssCode: (filename: string, cssCode: string) => Promise<string> | string;
|
||||
includeComponentCss?: boolean;
|
||||
}): Plugin;
|
||||
export declare function formatPostcssSourceMap(rawMap: ExistingRawSourceMap, file: string): ExistingRawSourceMap;
|
||||
export type CssUrlReplacer = (url: string, importer?: string, source?: PostCSS.Source) => string | Promise<string>;
|
||||
export declare const cssUrlRE: RegExp;
|
||||
export declare const cssDataUriRE: RegExp;
|
||||
export declare const importCssRE: RegExp;
|
||||
export declare function minifyCSS(css: string, config: ResolvedConfig): Promise<string>;
|
||||
export declare function hoistAtRules(css: string): Promise<string>;
|
||||
export interface StylePreprocessorResults {
|
||||
code: string;
|
||||
map?: ExistingRawSourceMap | undefined;
|
||||
additionalMap?: ExistingRawSourceMap | undefined;
|
||||
errors: RollupError[];
|
||||
deps: string[];
|
||||
}
|
||||
/**
|
||||
* 重写 readFileSync
|
||||
* 目前主要解决 scss 文件被 @import 的条件编译,如果用~@/方式导入,会走自定义importer,不需要通过重写readFileSync来过滤,所以nvue的问题,可以让开发者调整导入写法
|
||||
*/
|
||||
export declare function rewriteScssReadFileSync(): void;
|
||||
Generated
Vendored
+1170
File diff suppressed because it is too large
Load Diff
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
export declare function createIsStaticFile(): (relativeFile: string) => boolean;
|
||||
export declare function getIsStaticFile(): (file: string) => boolean;
|
||||
Generated
Vendored
+40
@@ -0,0 +1,40 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getIsStaticFile = exports.createIsStaticFile = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const utils_1 = require("../utils");
|
||||
const json_1 = require("../../../../json/json");
|
||||
const uniModulesStaticRe = /^uni_modules\/[^/]+\/static\//;
|
||||
function createIsStaticFile() {
|
||||
let subPackageStatics = [];
|
||||
const pagesFilename = path_1.default.join(process.env.UNI_INPUT_DIR, 'pages.json');
|
||||
if (fs_1.default.existsSync(pagesFilename)) {
|
||||
const pagesJson = (0, json_1.parseJson)(fs_1.default.readFileSync(pagesFilename, 'utf8'), true, pagesFilename);
|
||||
subPackageStatics = (pagesJson.subPackages || pagesJson.subpackages || [])
|
||||
.filter((subPackage) => subPackage.root)
|
||||
.map((subPackage) => {
|
||||
return (0, utils_1.normalizePath)(path_1.default.join(subPackage.root, 'static')) + '/';
|
||||
});
|
||||
}
|
||||
return function isStaticFile(relativeFile) {
|
||||
if (path_1.default.isAbsolute(relativeFile)) {
|
||||
relativeFile = (0, utils_1.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, relativeFile));
|
||||
}
|
||||
return (relativeFile.startsWith('static/') ||
|
||||
uniModulesStaticRe.test(relativeFile) ||
|
||||
subPackageStatics.some((s) => relativeFile.startsWith(s)));
|
||||
};
|
||||
}
|
||||
exports.createIsStaticFile = createIsStaticFile;
|
||||
let isStaticFile;
|
||||
function getIsStaticFile() {
|
||||
if (!isStaticFile) {
|
||||
isStaticFile = createIsStaticFile();
|
||||
}
|
||||
return isStaticFile;
|
||||
}
|
||||
exports.getIsStaticFile = getIsStaticFile;
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export type { ModuleNode } from 'vite';
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
Generated
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
import type { DecodedSourceMap, RawSourceMap } from '@ampproject/remapping';
|
||||
import type { Position, SourceLocation } from '@vue/compiler-core';
|
||||
import { LinesAndColumns } from 'lines-and-columns';
|
||||
export declare function slash(p: string): string;
|
||||
export declare const bareImportRE: RegExp;
|
||||
export declare const deepImportRE: RegExp;
|
||||
export declare const isWindows: boolean;
|
||||
export declare function normalizePath(id: string): string;
|
||||
export declare const queryRE: RegExp;
|
||||
export declare const hashRE: RegExp;
|
||||
export declare const cleanUrl: (url: string) => string;
|
||||
export declare const externalRE: RegExp;
|
||||
export declare const isExternalUrl: (url: string) => boolean;
|
||||
export declare const dataUrlRE: RegExp;
|
||||
export declare const isDataUrl: (url: string) => boolean;
|
||||
export declare const multilineCommentsRE: RegExp;
|
||||
export declare function asyncReplace(input: string, re: RegExp, replacer: (match: RegExpExecArray) => string | Promise<string>): Promise<string>;
|
||||
export declare function isObject(value: unknown): value is Record<string, any>;
|
||||
export declare function pad(source: string, n?: number): string;
|
||||
export declare function offsetToStartAndEnd(source: string, startOffset: number, endOffset: number): SourceLocation;
|
||||
export declare function offsetToLineColumn(source: string, offset: number): {
|
||||
line: number;
|
||||
column: number;
|
||||
};
|
||||
export declare function offsetToLineColumnByLines(lines: LinesAndColumns, offset: number): Position;
|
||||
export declare function posToNumber(source: string, pos: number | {
|
||||
line: number;
|
||||
column: number;
|
||||
}): number;
|
||||
export declare function locToStartAndEnd(source: string, loc: {
|
||||
start: {
|
||||
line: number;
|
||||
column: number;
|
||||
};
|
||||
end: {
|
||||
line: number;
|
||||
column: number;
|
||||
};
|
||||
}): {
|
||||
start: number;
|
||||
end: number | undefined;
|
||||
};
|
||||
export declare function generateCodeFrame(source: string, start?: number | {
|
||||
line: number;
|
||||
column: number;
|
||||
}, end?: number): string;
|
||||
interface ImageCandidate {
|
||||
url: string;
|
||||
descriptor: string;
|
||||
}
|
||||
export declare function processSrcSet(srcs: string, replacer: (arg: ImageCandidate) => Promise<string>): Promise<string>;
|
||||
export declare function combineSourcemaps(filename: string, sourcemapList: Array<DecodedSourceMap | RawSourceMap>, excludeContent?: boolean): RawSourceMap;
|
||||
export {};
|
||||
Generated
Vendored
+241
@@ -0,0 +1,241 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.combineSourcemaps = exports.processSrcSet = exports.generateCodeFrame = exports.locToStartAndEnd = exports.posToNumber = exports.offsetToLineColumnByLines = exports.offsetToLineColumn = exports.offsetToStartAndEnd = exports.pad = exports.isObject = exports.asyncReplace = exports.multilineCommentsRE = exports.isDataUrl = exports.dataUrlRE = exports.isExternalUrl = exports.externalRE = exports.cleanUrl = exports.hashRE = exports.queryRE = exports.normalizePath = exports.isWindows = exports.deepImportRE = exports.bareImportRE = exports.slash = void 0;
|
||||
/**
|
||||
* https://github.com/vitejs/vite/blob/main/packages/vite/src/node/utils.ts
|
||||
*/
|
||||
const os_1 = __importDefault(require("os"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const remapping_1 = __importDefault(require("@ampproject/remapping"));
|
||||
const lines_and_columns_1 = require("lines-and-columns");
|
||||
function slash(p) {
|
||||
return p.replace(/\\/g, '/');
|
||||
}
|
||||
exports.slash = slash;
|
||||
exports.bareImportRE = /^[\w@](?!.*:\/\/)/;
|
||||
exports.deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
|
||||
exports.isWindows = os_1.default.platform() === 'win32';
|
||||
function normalizePath(id) {
|
||||
return path_1.default.posix.normalize(exports.isWindows ? slash(id) : id);
|
||||
}
|
||||
exports.normalizePath = normalizePath;
|
||||
exports.queryRE = /\?.*$/s;
|
||||
exports.hashRE = /#.*$/s;
|
||||
const cleanUrl = (url) => url.replace(exports.hashRE, '').replace(exports.queryRE, '');
|
||||
exports.cleanUrl = cleanUrl;
|
||||
exports.externalRE = /^(https?:)?\/\//;
|
||||
const isExternalUrl = (url) => exports.externalRE.test(url);
|
||||
exports.isExternalUrl = isExternalUrl;
|
||||
exports.dataUrlRE = /^\s*data:/i;
|
||||
const isDataUrl = (url) => exports.dataUrlRE.test(url);
|
||||
exports.isDataUrl = isDataUrl;
|
||||
exports.multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm;
|
||||
async function asyncReplace(input, re, replacer) {
|
||||
let match;
|
||||
let remaining = input;
|
||||
let rewritten = '';
|
||||
while ((match = re.exec(remaining))) {
|
||||
rewritten += remaining.slice(0, match.index);
|
||||
rewritten += await replacer(match);
|
||||
remaining = remaining.slice(match.index + match[0].length);
|
||||
}
|
||||
rewritten += remaining;
|
||||
return rewritten;
|
||||
}
|
||||
exports.asyncReplace = asyncReplace;
|
||||
function isObject(value) {
|
||||
return Object.prototype.toString.call(value) === '[object Object]';
|
||||
}
|
||||
exports.isObject = isObject;
|
||||
const splitRE = /\r?\n/;
|
||||
const range = 2;
|
||||
function pad(source, n = 2) {
|
||||
const lines = source.split(splitRE);
|
||||
return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
|
||||
}
|
||||
exports.pad = pad;
|
||||
function offsetToStartAndEnd(source, startOffset, endOffset) {
|
||||
const lines = new lines_and_columns_1.LinesAndColumns(source);
|
||||
return {
|
||||
start: offsetToLineColumnByLines(lines, startOffset),
|
||||
end: offsetToLineColumnByLines(lines, endOffset),
|
||||
source: '',
|
||||
};
|
||||
}
|
||||
exports.offsetToStartAndEnd = offsetToStartAndEnd;
|
||||
function offsetToLineColumn(source, offset) {
|
||||
return offsetToLineColumnByLines(new lines_and_columns_1.LinesAndColumns(source), offset);
|
||||
}
|
||||
exports.offsetToLineColumn = offsetToLineColumn;
|
||||
function offsetToLineColumnByLines(lines, offset) {
|
||||
let location = lines.locationForIndex(offset);
|
||||
if (!location) {
|
||||
location = lines.locationForIndex(offset);
|
||||
}
|
||||
// lines-and-columns is 0-indexed while positions are 1-indexed
|
||||
return { line: location.line + 1, column: location.column, offset: 0 };
|
||||
}
|
||||
exports.offsetToLineColumnByLines = offsetToLineColumnByLines;
|
||||
function posToNumber(source, pos) {
|
||||
if (typeof pos === 'number')
|
||||
return pos;
|
||||
return posToNumberByLines(new lines_and_columns_1.LinesAndColumns(source), pos.line, pos.column);
|
||||
}
|
||||
exports.posToNumber = posToNumber;
|
||||
function posToNumberByLines(lines, line, column) {
|
||||
// lines-and-columns is 0-indexed while positions are 1-indexed
|
||||
return lines.indexForLocation({ line: line - 1, column }) || 0;
|
||||
}
|
||||
function locToStartAndEnd(source, loc) {
|
||||
const lines = new lines_and_columns_1.LinesAndColumns(source);
|
||||
const start = posToNumberByLines(lines, loc.start.line, loc.start.column);
|
||||
const end = loc.end
|
||||
? posToNumberByLines(lines, loc.end.line, loc.end.column)
|
||||
: undefined;
|
||||
return { start, end };
|
||||
}
|
||||
exports.locToStartAndEnd = locToStartAndEnd;
|
||||
function generateCodeFrame(source, start = 0, end) {
|
||||
start = posToNumber(source, start);
|
||||
end = end || start;
|
||||
// Split the content into individual lines but capture the newline sequence
|
||||
// that separated each line. This is important because the actual sequence is
|
||||
// needed to properly take into account the full line length for offset
|
||||
// comparison
|
||||
let lines = source.split(/(\r?\n)/);
|
||||
// Separate the lines and newline sequences into separate arrays for easier referencing
|
||||
const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
|
||||
lines = lines.filter((_, idx) => idx % 2 === 0);
|
||||
let count = 0;
|
||||
const res = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
count +=
|
||||
lines[i].length +
|
||||
((newlineSequences[i] && newlineSequences[i].length) || 0);
|
||||
if (count >= start) {
|
||||
for (let j = i - range; j <= i + range || end > count; j++) {
|
||||
if (j < 0 || j >= lines.length)
|
||||
continue;
|
||||
const line = j + 1;
|
||||
res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
|
||||
const lineLength = lines[j].length;
|
||||
const newLineSeqLength = (newlineSequences[j] && newlineSequences[j].length) || 0;
|
||||
if (j === i) {
|
||||
// push underline
|
||||
const pad = start - (count - (lineLength + newLineSeqLength));
|
||||
const length = Math.max(1, end > count ? lineLength - pad : end - start);
|
||||
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
|
||||
}
|
||||
else if (j > i) {
|
||||
if (end > count) {
|
||||
const length = Math.max(Math.min(end - count, lineLength), 1);
|
||||
res.push(` | ` + '^'.repeat(length));
|
||||
}
|
||||
count += lineLength + newLineSeqLength;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res.join('\n');
|
||||
}
|
||||
exports.generateCodeFrame = generateCodeFrame;
|
||||
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
|
||||
const imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/;
|
||||
async function processSrcSet(srcs, replacer) {
|
||||
const imageCandidates = srcs
|
||||
.split(',')
|
||||
.map((s) => {
|
||||
const src = s.replace(escapedSpaceCharacters, ' ').trim();
|
||||
const [url] = imageSetUrlRE.exec(src) || [];
|
||||
return {
|
||||
url: url,
|
||||
descriptor: src?.slice(url.length).trim(),
|
||||
};
|
||||
})
|
||||
.filter(({ url }) => !!url);
|
||||
const ret = await Promise.all(imageCandidates.map(async ({ url, descriptor }) => {
|
||||
return {
|
||||
url: await replacer({ url, descriptor }),
|
||||
descriptor,
|
||||
};
|
||||
}));
|
||||
const url = ret.reduce((prev, { url, descriptor }, index) => {
|
||||
descriptor = descriptor || '';
|
||||
return (prev +=
|
||||
url + ` ${descriptor}${index === ret.length - 1 ? '' : ', '}`);
|
||||
}, '');
|
||||
return url;
|
||||
}
|
||||
exports.processSrcSet = processSrcSet;
|
||||
function escapeToLinuxLikePath(path) {
|
||||
if (/^[A-Z]:/.test(path)) {
|
||||
return path.replace(/^([A-Z]):\//, '/windows/$1/');
|
||||
}
|
||||
if (/^\/[^/]/.test(path)) {
|
||||
return `/linux${path}`;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
function unescapeToLinuxLikePath(path) {
|
||||
if (path.startsWith('/linux/')) {
|
||||
return path.slice('/linux'.length);
|
||||
}
|
||||
if (path.startsWith('/windows/')) {
|
||||
return path.replace(/^\/windows\/([A-Z])\//, '$1:/');
|
||||
}
|
||||
return path;
|
||||
}
|
||||
// based on https://github.com/sveltejs/svelte/blob/abf11bb02b2afbd3e4cac509a0f70e318c306364/src/compiler/utils/mapped_code.ts#L221
|
||||
const nullSourceMap = {
|
||||
names: [],
|
||||
sources: [],
|
||||
mappings: '',
|
||||
version: 3,
|
||||
};
|
||||
function combineSourcemaps(filename, sourcemapList, excludeContent = true) {
|
||||
if (sourcemapList.length === 0 ||
|
||||
sourcemapList.every((m) => m.sources.length === 0)) {
|
||||
return { ...nullSourceMap };
|
||||
}
|
||||
// hack for parse broken with normalized absolute paths on windows (C:/path/to/something).
|
||||
// escape them to linux like paths
|
||||
// also avoid mutation here to prevent breaking plugin's using cache to generate sourcemaps like vue (see #7442)
|
||||
sourcemapList = sourcemapList.map((sourcemap) => {
|
||||
const newSourcemaps = { ...sourcemap };
|
||||
newSourcemaps.sources = sourcemap.sources.map((source) => source ? escapeToLinuxLikePath(source) : null);
|
||||
if (sourcemap.sourceRoot) {
|
||||
newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
|
||||
}
|
||||
return newSourcemaps;
|
||||
});
|
||||
const escapedFilename = escapeToLinuxLikePath(filename);
|
||||
// We don't declare type here so we can convert/fake/map as RawSourceMap
|
||||
let map; //: SourceMap
|
||||
let mapIndex = 1;
|
||||
const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === undefined;
|
||||
if (useArrayInterface) {
|
||||
map = (0, remapping_1.default)(sourcemapList, () => null, excludeContent);
|
||||
}
|
||||
else {
|
||||
map = (0, remapping_1.default)(sourcemapList[0], function loader(sourcefile) {
|
||||
if (sourcefile === escapedFilename && sourcemapList[mapIndex]) {
|
||||
return sourcemapList[mapIndex++];
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}, excludeContent);
|
||||
}
|
||||
if (!map.file) {
|
||||
delete map.file;
|
||||
}
|
||||
// unescape the previous hack
|
||||
map.sources = map.sources.map((source) => source ? unescapeToLinuxLikePath(source) : source);
|
||||
map.file = filename;
|
||||
return map;
|
||||
}
|
||||
exports.combineSourcemaps = combineSourcemaps;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import type { AssignmentExpression, BaseNode, CallExpression, ExportSpecifier, Identifier, Literal, MemberExpression, MethodDefinition, Property } from 'estree';
|
||||
import { type AttributeNode, type CompoundExpressionNode, type DirectiveNode, type ElementNode, type Node, type SimpleExpressionNode } from '@vue/compiler-core';
|
||||
export declare const isProperty: (node: BaseNode) => node is Property;
|
||||
export declare const isIdentifier: (node: BaseNode) => node is Identifier;
|
||||
export declare const isAssignmentExpression: (node: BaseNode) => node is AssignmentExpression;
|
||||
export declare const isCallExpression: (node: BaseNode) => node is CallExpression;
|
||||
export declare const isMemberExpression: (node: BaseNode) => node is MemberExpression;
|
||||
export declare const isMethodDefinition: (node: BaseNode) => node is MethodDefinition;
|
||||
export declare const isExportSpecifier: (node: BaseNode) => node is ExportSpecifier;
|
||||
export declare const isReference: (node: BaseNode, parent: BaseNode) => boolean;
|
||||
export declare function createLiteral(value: string): Literal;
|
||||
export declare function createIdentifier(name: string): Identifier;
|
||||
export declare function createCallExpression(callee: unknown, args: unknown[]): CallExpression;
|
||||
export declare function parseVue(code: string, errors: SyntaxError[]): import("@vue/compiler-core").RootNode;
|
||||
export declare function isElementNode(node: Node): node is ElementNode;
|
||||
export declare function isAttributeNode(node: Node): node is AttributeNode;
|
||||
export declare function isDirectiveNode(node: Node): node is DirectiveNode;
|
||||
export declare function isSimpleExpressionNode(node: Node): node is SimpleExpressionNode;
|
||||
export declare function isCompoundExpressionNode(node: Node): node is CompoundExpressionNode;
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isCompoundExpressionNode = exports.isSimpleExpressionNode = exports.isDirectiveNode = exports.isAttributeNode = exports.isElementNode = exports.parseVue = exports.createCallExpression = exports.createIdentifier = exports.createLiteral = exports.isReference = exports.isExportSpecifier = exports.isMethodDefinition = exports.isMemberExpression = exports.isCallExpression = exports.isAssignmentExpression = exports.isIdentifier = exports.isProperty = void 0;
|
||||
const compiler_core_1 = require("@vue/compiler-core");
|
||||
const compiler_dom_1 = require("@vue/compiler-dom");
|
||||
const isProperty = (node) => node.type === 'Property';
|
||||
exports.isProperty = isProperty;
|
||||
const isIdentifier = (node) => node.type === 'Identifier';
|
||||
exports.isIdentifier = isIdentifier;
|
||||
const isAssignmentExpression = (node) => node.type === 'AssignmentExpression';
|
||||
exports.isAssignmentExpression = isAssignmentExpression;
|
||||
const isCallExpression = (node) => node.type === 'CallExpression';
|
||||
exports.isCallExpression = isCallExpression;
|
||||
const isMemberExpression = (node) => node.type === 'MemberExpression';
|
||||
exports.isMemberExpression = isMemberExpression;
|
||||
const isMethodDefinition = (node) => node.type === 'MethodDefinition';
|
||||
exports.isMethodDefinition = isMethodDefinition;
|
||||
const isExportSpecifier = (node) => node.type === 'ExportSpecifier';
|
||||
exports.isExportSpecifier = isExportSpecifier;
|
||||
const isReference = (node, parent) => {
|
||||
if ((0, exports.isMemberExpression)(node)) {
|
||||
return !node.computed && (0, exports.isReference)(node.object, node);
|
||||
}
|
||||
if ((0, exports.isIdentifier)(node)) {
|
||||
if ((0, exports.isMemberExpression)(parent))
|
||||
return parent.computed || node === parent.object;
|
||||
// `bar` in { bar: foo }
|
||||
if ((0, exports.isProperty)(parent) && node !== parent.value)
|
||||
return false;
|
||||
// `bar` in `class Foo { bar () {...} }`
|
||||
if ((0, exports.isMethodDefinition)(parent))
|
||||
return false;
|
||||
// `bar` in `export { foo as bar }`
|
||||
if ((0, exports.isExportSpecifier)(parent) && node !== parent.local)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
exports.isReference = isReference;
|
||||
function createLiteral(value) {
|
||||
return {
|
||||
type: 'Literal',
|
||||
value,
|
||||
raw: `'${value}'`,
|
||||
};
|
||||
}
|
||||
exports.createLiteral = createLiteral;
|
||||
function createIdentifier(name) {
|
||||
return {
|
||||
type: 'Identifier',
|
||||
name,
|
||||
};
|
||||
}
|
||||
exports.createIdentifier = createIdentifier;
|
||||
function createCallExpression(callee, args) {
|
||||
return {
|
||||
type: 'CallExpression',
|
||||
callee,
|
||||
arguments: args,
|
||||
};
|
||||
}
|
||||
exports.createCallExpression = createCallExpression;
|
||||
function parseVue(code, errors) {
|
||||
return (0, compiler_dom_1.parse)(code, {
|
||||
isNativeTag: () => true,
|
||||
isPreTag: () => true,
|
||||
parseMode: 'sfc',
|
||||
onError: (e) => {
|
||||
errors.push(e);
|
||||
},
|
||||
});
|
||||
}
|
||||
exports.parseVue = parseVue;
|
||||
function isElementNode(node) {
|
||||
return node.type === compiler_core_1.NodeTypes.ELEMENT;
|
||||
}
|
||||
exports.isElementNode = isElementNode;
|
||||
function isAttributeNode(node) {
|
||||
return node.type === compiler_core_1.NodeTypes.ATTRIBUTE;
|
||||
}
|
||||
exports.isAttributeNode = isAttributeNode;
|
||||
function isDirectiveNode(node) {
|
||||
return node.type === compiler_core_1.NodeTypes.DIRECTIVE;
|
||||
}
|
||||
exports.isDirectiveNode = isDirectiveNode;
|
||||
function isSimpleExpressionNode(node) {
|
||||
return node.type === compiler_core_1.NodeTypes.SIMPLE_EXPRESSION;
|
||||
}
|
||||
exports.isSimpleExpressionNode = isSimpleExpressionNode;
|
||||
function isCompoundExpressionNode(node) {
|
||||
return node.type === compiler_core_1.NodeTypes.COMPOUND_EXPRESSION;
|
||||
}
|
||||
exports.isCompoundExpressionNode = isCompoundExpressionNode;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
export * from './ast';
|
||||
export * from './url';
|
||||
export * from './plugin';
|
||||
export * from './utils';
|
||||
export declare const buildInCssSet: Set<string>;
|
||||
export declare function isCombineBuiltInCss(config: ResolvedConfig): boolean;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"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 __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isCombineBuiltInCss = exports.buildInCssSet = void 0;
|
||||
const utils_1 = require("../../utils");
|
||||
__exportStar(require("./ast"), exports);
|
||||
__exportStar(require("./url"), exports);
|
||||
__exportStar(require("./plugin"), exports);
|
||||
__exportStar(require("./utils"), exports);
|
||||
// 内置组件css列表,h5平台需要合并进去首页css中
|
||||
exports.buildInCssSet = new Set();
|
||||
function isCombineBuiltInCss(config) {
|
||||
if (!(0, utils_1.isNormalCompileTarget)()) {
|
||||
return false;
|
||||
}
|
||||
return config.command === 'build' && config.build.cssCodeSplit;
|
||||
}
|
||||
exports.isCombineBuiltInCss = isCombineBuiltInCss;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import type { Plugin, ResolveFn, ResolvedConfig } from 'vite';
|
||||
import { type CssUrlReplacer } from '../plugins/vitejs/plugins/css';
|
||||
export type CreateUniViteFilterPlugin = (opts: UniViteFilterPluginOptions) => Plugin;
|
||||
export interface UniViteFilterPluginOptions {
|
||||
resolvedConfig: ResolvedConfig;
|
||||
filter: (id: string) => boolean;
|
||||
}
|
||||
export declare function injectAssetPlugin(config: ResolvedConfig, options?: {
|
||||
isAndroidX: boolean;
|
||||
}): void;
|
||||
export declare function injectCssPlugin(config: ResolvedConfig, options?: {
|
||||
createUrlReplacer?: (resolve: ResolveFn) => CssUrlReplacer;
|
||||
}): void;
|
||||
export declare function injectCssPostPlugin(config: ResolvedConfig, newCssPostPlugin: Plugin): void;
|
||||
export declare function replacePlugins(plugins: Plugin[], config: ResolvedConfig): void;
|
||||
export declare function removePlugins(plugins: string | string[], config: ResolvedConfig): void;
|
||||
export declare function insertBeforePlugin(plugin: Plugin, before: string, config: ResolvedConfig): void;
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.insertBeforePlugin = exports.removePlugins = exports.replacePlugins = exports.injectCssPostPlugin = exports.injectCssPlugin = exports.injectAssetPlugin = void 0;
|
||||
const shared_1 = require("@vue/shared");
|
||||
const asset_1 = require("../plugins/vitejs/plugins/asset");
|
||||
const css_1 = require("../plugins/vitejs/plugins/css");
|
||||
function injectAssetPlugin(config, options) {
|
||||
replacePlugins([(0, asset_1.assetPlugin)(config, options)], config);
|
||||
}
|
||||
exports.injectAssetPlugin = injectAssetPlugin;
|
||||
function injectCssPlugin(config, options) {
|
||||
replacePlugins([
|
||||
(0, css_1.cssPlugin)(config, {
|
||||
isAndroidX: false,
|
||||
...options,
|
||||
}),
|
||||
], config);
|
||||
}
|
||||
exports.injectCssPlugin = injectCssPlugin;
|
||||
function injectCssPostPlugin(config, newCssPostPlugin) {
|
||||
const oldCssPostPlugin = config.plugins.find((p) => p.name === newCssPostPlugin.name);
|
||||
// 直接覆盖原有方法,不能删除,替换,因为 unocss 在 pre 阶段已经获取到了旧的 css-post 插件对象
|
||||
if (oldCssPostPlugin) {
|
||||
(0, shared_1.extend)(oldCssPostPlugin, newCssPostPlugin);
|
||||
}
|
||||
}
|
||||
exports.injectCssPostPlugin = injectCssPostPlugin;
|
||||
function replacePlugins(plugins, config) {
|
||||
plugins.forEach((plugin) => {
|
||||
const index = config.plugins.findIndex((p) => p.name === plugin.name);
|
||||
if (index > -1) {
|
||||
;
|
||||
config.plugins.splice(index, 1, plugin);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.replacePlugins = replacePlugins;
|
||||
function removePlugins(plugins, config) {
|
||||
if (!(0, shared_1.isArray)(plugins)) {
|
||||
plugins = [plugins];
|
||||
}
|
||||
plugins.forEach((name) => {
|
||||
const index = config.plugins.findIndex((p) => p.name === name);
|
||||
if (index > -1) {
|
||||
;
|
||||
config.plugins.splice(index, 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.removePlugins = removePlugins;
|
||||
function insertBeforePlugin(plugin, before, config) {
|
||||
const index = config.plugins.findIndex((p) => p.name === before);
|
||||
if (index > -1) {
|
||||
;
|
||||
config.plugins.splice(index, 0, plugin);
|
||||
}
|
||||
}
|
||||
exports.insertBeforePlugin = insertBeforePlugin;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
export interface VueQuery {
|
||||
vue?: boolean;
|
||||
src?: boolean;
|
||||
type?: 'script' | 'template' | 'style' | 'custom' | 'page';
|
||||
index?: number;
|
||||
lang?: string;
|
||||
raw?: boolean;
|
||||
setup?: boolean;
|
||||
'lang.ts'?: string;
|
||||
'lang.js'?: string;
|
||||
}
|
||||
export declare function parseVueRequest(id: string): {
|
||||
filename: string;
|
||||
query: VueQuery;
|
||||
};
|
||||
export declare const isImportRequest: (url: string) => boolean;
|
||||
/**
|
||||
* Prefix for resolved fs paths, since windows paths may not be valid as URLs.
|
||||
*/
|
||||
export declare const FS_PREFIX = "/@fs/";
|
||||
/**
|
||||
* Prefix for resolved Ids that are not valid browser import specifiers
|
||||
*/
|
||||
export declare const VALID_ID_PREFIX = "/@id/";
|
||||
export declare const CLIENT_PUBLIC_PATH = "/@vite/client";
|
||||
export declare const ENV_PUBLIC_PATH = "/@vite/env";
|
||||
export declare const isInternalRequest: (url: string) => boolean;
|
||||
export declare const queryRE: RegExp;
|
||||
export declare const hashRE: RegExp;
|
||||
export declare const cleanUrl: (url: string) => string;
|
||||
export declare function isJsFile(id: string): boolean;
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isJsFile = exports.cleanUrl = exports.hashRE = exports.queryRE = exports.isInternalRequest = exports.ENV_PUBLIC_PATH = exports.CLIENT_PUBLIC_PATH = exports.VALID_ID_PREFIX = exports.FS_PREFIX = exports.isImportRequest = exports.parseVueRequest = void 0;
|
||||
const shared_1 = require("@vue/shared");
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const constants_1 = require("../../constants");
|
||||
function parseVueRequest(id) {
|
||||
const [filename, rawQuery] = id.split(`?`, 2);
|
||||
const query = Object.fromEntries(new URLSearchParams(rawQuery));
|
||||
if (query.vue != null) {
|
||||
query.vue = true;
|
||||
}
|
||||
if (query.src != null) {
|
||||
query.src = true;
|
||||
}
|
||||
if (query.index != null) {
|
||||
query.index = Number(query.index);
|
||||
}
|
||||
if (query.raw != null) {
|
||||
query.raw = true;
|
||||
}
|
||||
return {
|
||||
filename,
|
||||
query,
|
||||
};
|
||||
}
|
||||
exports.parseVueRequest = parseVueRequest;
|
||||
const importQueryRE = /(\?|&)import=?(?:&|$)/;
|
||||
const isImportRequest = (url) => importQueryRE.test(url);
|
||||
exports.isImportRequest = isImportRequest;
|
||||
/**
|
||||
* Prefix for resolved fs paths, since windows paths may not be valid as URLs.
|
||||
*/
|
||||
exports.FS_PREFIX = `/@fs/`;
|
||||
/**
|
||||
* Prefix for resolved Ids that are not valid browser import specifiers
|
||||
*/
|
||||
exports.VALID_ID_PREFIX = `/@id/`;
|
||||
exports.CLIENT_PUBLIC_PATH = `/@vite/client`;
|
||||
exports.ENV_PUBLIC_PATH = `/@vite/env`;
|
||||
const internalPrefixes = [
|
||||
exports.FS_PREFIX,
|
||||
exports.VALID_ID_PREFIX,
|
||||
exports.CLIENT_PUBLIC_PATH,
|
||||
exports.ENV_PUBLIC_PATH,
|
||||
];
|
||||
const InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join('|')})`);
|
||||
const isInternalRequest = (url) => InternalPrefixRE.test(url);
|
||||
exports.isInternalRequest = isInternalRequest;
|
||||
exports.queryRE = /\?.*$/;
|
||||
exports.hashRE = /#.*$/;
|
||||
const cleanUrl = (url) => url.replace(exports.hashRE, '').replace(exports.queryRE, '');
|
||||
exports.cleanUrl = cleanUrl;
|
||||
function isJsFile(id) {
|
||||
const { filename, query } = parseVueRequest(id);
|
||||
const isJs = constants_1.EXTNAME_JS_RE.test(filename);
|
||||
if (isJs) {
|
||||
return true;
|
||||
}
|
||||
const isVueJs = constants_1.EXTNAME_VUE.includes(path_1.default.extname(filename)) &&
|
||||
(!query.vue ||
|
||||
query.setup ||
|
||||
(0, shared_1.hasOwn)(query, 'lang.ts') ||
|
||||
(0, shared_1.hasOwn)(query, 'lang.js') ||
|
||||
(0, shared_1.hasOwn)(query, 'lang.uts'));
|
||||
if (isVueJs) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
exports.isJsFile = isJsFile;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import type { ConfigEnv, ResolvedConfig, UserConfig } from 'vite';
|
||||
import type { RollupError } from 'rollup';
|
||||
import type { CompilerError } from '@vue/compiler-sfc';
|
||||
import { codeFrameColumns } from '@babel/code-frame';
|
||||
export declare function withSourcemap(config: ResolvedConfig): boolean;
|
||||
export declare function isInHybridNVue(config: UserConfig | ResolvedConfig): boolean;
|
||||
export declare function isSsr(command: ConfigEnv['command'], config: UserConfig | ResolvedConfig): boolean;
|
||||
export declare function createRollupError(plugin: string, id: string, error: CompilerError | SyntaxError, source?: string): RollupError;
|
||||
export declare const generateCodeFrameColumns: typeof codeFrameColumns;
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.generateCodeFrameColumns = exports.createRollupError = exports.isSsr = exports.isInHybridNVue = exports.withSourcemap = void 0;
|
||||
const shared_1 = require("@vue/shared");
|
||||
const code_frame_1 = require("@babel/code-frame");
|
||||
const utils_1 = require("../plugins/vitejs/utils");
|
||||
const utils_2 = require("../../utils");
|
||||
function withSourcemap(config) {
|
||||
if (!process.env.UNI_APP_SOURCEMAP) {
|
||||
if (config.build && (0, shared_1.hasOwn)(config.build, 'sourcemap')) {
|
||||
if (!!config.build.sourcemap) {
|
||||
process.env.UNI_APP_SOURCEMAP = 'true';
|
||||
}
|
||||
else {
|
||||
// vite 的 build 模式默认是false,而非web端的dev也是用build模式,所以不能这样判断
|
||||
// process.env.UNI_APP_SOURCEMAP = 'false'
|
||||
}
|
||||
}
|
||||
}
|
||||
return (0, utils_2.enableSourceMap)();
|
||||
}
|
||||
exports.withSourcemap = withSourcemap;
|
||||
function isInHybridNVue(config) {
|
||||
return config.nvue && process.env.UNI_RENDERER !== 'native';
|
||||
}
|
||||
exports.isInHybridNVue = isInHybridNVue;
|
||||
function isSsr(command, config) {
|
||||
if (command === 'serve') {
|
||||
return !!(config.server && config.server.middlewareMode);
|
||||
}
|
||||
if (command === 'build') {
|
||||
return !!(config.build && config.build.ssr);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
exports.isSsr = isSsr;
|
||||
function createRollupError(plugin, id, error, source) {
|
||||
const { message, name, stack } = error;
|
||||
const rollupError = (0, shared_1.extend)(new Error(message), {
|
||||
id,
|
||||
plugin,
|
||||
name,
|
||||
stack,
|
||||
});
|
||||
if ('code' in error && error.loc) {
|
||||
rollupError.loc = {
|
||||
file: id,
|
||||
line: error.loc.start.line,
|
||||
column: error.loc.start.column,
|
||||
};
|
||||
if (source && source.length > 0) {
|
||||
if ('offsetStart' in error && 'offsetEnd' in error) {
|
||||
rollupError.frame = (0, code_frame_1.codeFrameColumns)(source, (0, utils_1.offsetToStartAndEnd)(source, error.offsetStart, error.offsetEnd));
|
||||
}
|
||||
else {
|
||||
rollupError.frame = (0, code_frame_1.codeFrameColumns)(source, error.loc);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (id) {
|
||||
// 指定了id后,不让后续的rollup重写
|
||||
Object.defineProperty(rollupError, 'id', {
|
||||
get() {
|
||||
return id;
|
||||
},
|
||||
set(_v) { },
|
||||
});
|
||||
}
|
||||
return rollupError;
|
||||
}
|
||||
exports.createRollupError = createRollupError;
|
||||
exports.generateCodeFrameColumns = code_frame_1.codeFrameColumns;
|
||||
Reference in New Issue
Block a user