gengx
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import type { ArchiverPluginOptions } from '../typing';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
|
||||
import { ZipArchive } from 'archiver';
|
||||
|
||||
export const viteArchiverPlugin = (
|
||||
options: ArchiverPluginOptions = {},
|
||||
): PluginOption => {
|
||||
return {
|
||||
apply: 'build',
|
||||
closeBundle: {
|
||||
handler() {
|
||||
const { name = 'dist', outputDir = '.' } = options;
|
||||
|
||||
setTimeout(async () => {
|
||||
const folderToZip = 'dist';
|
||||
|
||||
const zipOutputDir = join(process.cwd(), outputDir);
|
||||
const zipOutputPath = join(zipOutputDir, `${name}.zip`);
|
||||
try {
|
||||
await fsp.mkdir(zipOutputDir, { recursive: true });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
try {
|
||||
await zipFolder(folderToZip, zipOutputPath);
|
||||
console.log(`Folder has been zipped to: ${zipOutputPath}`);
|
||||
} catch (error) {
|
||||
console.error('Error zipping folder:', error);
|
||||
}
|
||||
}, 0);
|
||||
},
|
||||
order: 'post',
|
||||
},
|
||||
enforce: 'post',
|
||||
name: 'vite:archiver',
|
||||
};
|
||||
};
|
||||
|
||||
async function zipFolder(
|
||||
folderPath: string,
|
||||
outputPath: string,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const output = fs.createWriteStream(outputPath);
|
||||
|
||||
const archive = new ZipArchive({
|
||||
zlib: { level: 9 }, // 设置压缩级别为 9 以实现最高压缩率
|
||||
});
|
||||
|
||||
output.on('close', () => {
|
||||
console.log(
|
||||
`ZIP file created: ${outputPath} (${archive.pointer()} total bytes)`,
|
||||
);
|
||||
resolve();
|
||||
});
|
||||
|
||||
archive.on('error', (err) => {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
archive.pipe(output);
|
||||
|
||||
// 使用 directory 方法以流的方式压缩文件夹,减少内存消耗
|
||||
archive.directory(folderPath, false);
|
||||
|
||||
// 流式处理完成
|
||||
archive.finalize();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { viteCssLayerPlugin } from './css-layer';
|
||||
|
||||
interface FakeAsset {
|
||||
fileName: string;
|
||||
source: string;
|
||||
type: string;
|
||||
}
|
||||
|
||||
function createBundle(assets: FakeAsset[]) {
|
||||
return Object.fromEntries(assets.map((asset) => [asset.fileName, asset]));
|
||||
}
|
||||
|
||||
const LAYER_ORDER_STATEMENT =
|
||||
'@layer properties, theme, base, ant, antd, el, td, components, utilities;';
|
||||
|
||||
describe('viteCssLayerPlugin', () => {
|
||||
it('wraps matching css modules in the target layer', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const transform = plugin.transform;
|
||||
|
||||
if (typeof transform !== 'function') return;
|
||||
|
||||
const result = transform.call(
|
||||
undefined as never,
|
||||
'.el-button { color: red; }',
|
||||
'/node_modules/element-plus/es/components/button/style/css/index.css?used',
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
code: '@layer el {\n.el-button { color: red; }\n}',
|
||||
map: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not wrap css modules outside the target package', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const transform = plugin.transform;
|
||||
|
||||
if (typeof transform !== 'function') return;
|
||||
|
||||
const result = transform.call(
|
||||
undefined as never,
|
||||
'.local { color: red; }',
|
||||
'/src/views/home/index.css',
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('injects the layer order statement into matching css assets', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const generateBundle = plugin.generateBundle;
|
||||
|
||||
if (typeof generateBundle !== 'function') return;
|
||||
|
||||
const bundle = createBundle([
|
||||
{
|
||||
fileName: 'element-x.css',
|
||||
source: '@layer el{.el-button{color:red}}',
|
||||
type: 'asset',
|
||||
},
|
||||
{
|
||||
fileName: 'theme-x.css',
|
||||
source: '.local { color: blue; }',
|
||||
type: 'asset',
|
||||
},
|
||||
]);
|
||||
|
||||
generateBundle.call(undefined as never, {} as never, bundle);
|
||||
|
||||
expect(bundle['element-x.css'].source).toBe(
|
||||
`${LAYER_ORDER_STATEMENT}\n@layer el{.el-button{color:red}}`,
|
||||
);
|
||||
expect(bundle['theme-x.css'].source).toBe('.local { color: blue; }');
|
||||
});
|
||||
|
||||
it('does not inject the statement twice when already present', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const generateBundle = plugin.generateBundle;
|
||||
|
||||
if (typeof generateBundle !== 'function') return;
|
||||
|
||||
const bundle = createBundle([
|
||||
{
|
||||
fileName: 'element-x.css',
|
||||
source: `${LAYER_ORDER_STATEMENT}\n@layer el{.el-button{color:red}}`,
|
||||
type: 'asset',
|
||||
},
|
||||
]);
|
||||
|
||||
generateBundle.call(undefined as never, {} as never, bundle);
|
||||
|
||||
expect(bundle['element-x.css'].source).toBe(
|
||||
`${LAYER_ORDER_STATEMENT}\n@layer el{.el-button{color:red}}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('injects the statement even when the asset starts with a BOM', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const generateBundle = plugin.generateBundle;
|
||||
|
||||
if (typeof generateBundle !== 'function') return;
|
||||
|
||||
const bundle = createBundle([
|
||||
{
|
||||
fileName: 'element-x.css',
|
||||
source: `\uFEFF@layer el{.el-button{color:red}}`,
|
||||
type: 'asset',
|
||||
},
|
||||
]);
|
||||
|
||||
generateBundle.call(undefined as never, {} as never, bundle);
|
||||
|
||||
expect(bundle['element-x.css'].source).toBe(
|
||||
`${LAYER_ORDER_STATEMENT}\n\uFEFF@layer el{.el-button{color:red}}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores non-css assets', () => {
|
||||
const plugin = viteCssLayerPlugin({
|
||||
layerName: 'el',
|
||||
packageName: 'element-plus',
|
||||
});
|
||||
const generateBundle = plugin.generateBundle;
|
||||
|
||||
if (typeof generateBundle !== 'function') return;
|
||||
|
||||
const bundle = createBundle([
|
||||
{
|
||||
fileName: 'element-x.js',
|
||||
source: '@layer el{.el-button{color:red}}',
|
||||
type: 'chunk',
|
||||
},
|
||||
]);
|
||||
|
||||
generateBundle.call(undefined as never, {} as never, bundle);
|
||||
|
||||
expect(bundle['element-x.js'].source).toBe(
|
||||
'@layer el{.el-button{color:red}}',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { Plugin } from 'vite';
|
||||
|
||||
interface CssLayerRule {
|
||||
/** 层名,需在 css 中先于 @import 'tailwindcss' 声明层顺序(见 internal/tailwind-config/theme.css) */
|
||||
layerName: string;
|
||||
/** 需要包层的包名(匹配该包在 node_modules 下的 css 模块 id) */
|
||||
packageName: string;
|
||||
}
|
||||
|
||||
function escapeRegExp(value: string): string {
|
||||
return value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 与 internal/tailwind-config/src/theme.css 中的层顺序保持一致:
|
||||
* properties(Tailwind 的 --tw-* 回退变量层) < preflight(base) <
|
||||
* UI 库组件样式(antd / el / td) < Tailwind 工具类。
|
||||
* 该声明必须在打包后注入:生产构建下 css 按 chunk 注入,若组件库的 css
|
||||
* chunk 先于含层顺序声明的 theme.css 加载,层名会先被注册为最低优先级,
|
||||
* 导致 Tailwind base/utilities 覆盖组件样式。打包后在每个含组件库层的
|
||||
* css 产物顶部补上该声明,无论 chunk 加载顺序如何,层优先级都正确
|
||||
* (theme.css 先加载时该声明是幂等的 no-op)。
|
||||
* 注意 properties 必须排在首位:它是 Tailwind 为不支持 @property 的旧
|
||||
* 浏览器准备的 --tw-* 回退变量层,必须始终是最低优先级,否则其回退声明
|
||||
* 会覆盖工具类写入的变量。
|
||||
*/
|
||||
const LAYER_ORDER_STATEMENT =
|
||||
'@layer properties, theme, base, ant, antd, el, td, components, utilities;';
|
||||
|
||||
/**
|
||||
* 把指定包内的 css 包进 @layer:
|
||||
* 组件库的 css 是无层样式,无层样式在级联中永远压过 @layer 内的 Tailwind 工具类;
|
||||
* 包层后由 theme.css 的层声明决定顺序(utilities 排在组件库层之后),
|
||||
* 使 Tailwind 工具类可以覆盖组件库样式。
|
||||
*
|
||||
* 注意:层顺序声明不能在 transform 阶段随包层 css 一起输出——rolldown-vite
|
||||
* 的 css 合并会将「层顺序声明 + @layer 规则」形式的模块拆层(规则被脱层),
|
||||
* 且产物压缩阶段也会丢弃该声明。因此改在 generateBundle 阶段对最终 css
|
||||
* 产物统一注入(见 LAYER_ORDER_STATEMENT)。
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* plugins: [viteCssLayerPlugin({ packageName: 'element-plus', layerName: 'el' })]
|
||||
* ```
|
||||
*/
|
||||
export function viteCssLayerPlugin(
|
||||
rules: CssLayerRule | CssLayerRule[],
|
||||
): Plugin {
|
||||
const list = Array.isArray(rules) ? rules : [rules];
|
||||
const matchers = list.map(({ layerName, packageName }) => ({
|
||||
layerName,
|
||||
regex: new RegExp(`${escapeRegExp(packageName)}[\\\\/].+\\.css$`, 'i'),
|
||||
}));
|
||||
return {
|
||||
name: 'vite-plugin-css-layer',
|
||||
enforce: 'pre',
|
||||
transform(code, id) {
|
||||
const [file] = id.split('?', 1);
|
||||
if (!file) return;
|
||||
const matched = matchers.find((m) => m.regex.test(file));
|
||||
if (matched) {
|
||||
return { code: `@layer ${matched.layerName} {\n${code}\n}`, map: null };
|
||||
}
|
||||
},
|
||||
generateBundle(_options, bundle) {
|
||||
for (const file of Object.values(bundle)) {
|
||||
if (file.type !== 'asset' || !file.fileName.endsWith('.css')) {
|
||||
continue;
|
||||
}
|
||||
const css = file.source.toString();
|
||||
const matched = matchers.some((m) =>
|
||||
css.includes(`@layer ${m.layerName}`),
|
||||
);
|
||||
if (!matched) {
|
||||
continue;
|
||||
}
|
||||
// 先去除可能的 BOM 再判断,避免重复注入层顺序声明
|
||||
const hasStatement = css
|
||||
.replace(/^\uFEFF/, '')
|
||||
.trimStart()
|
||||
.startsWith(LAYER_ORDER_STATEMENT);
|
||||
if (hasStatement) {
|
||||
continue;
|
||||
}
|
||||
file.source = `${LAYER_ORDER_STATEMENT}\n${css}`;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { Plugin } from 'vite';
|
||||
|
||||
function viteDayjsPlugin(): Plugin {
|
||||
return {
|
||||
name: 'vite-dayjs-plugin',
|
||||
enforce: 'pre',
|
||||
async resolveId(source, importer, options) {
|
||||
// 1) 已经使用了 dayjs/esm 的不处理
|
||||
if (source.startsWith('dayjs/esm')) return null;
|
||||
|
||||
// 2) 根入口:dayjs -> dayjs/esm
|
||||
if (source === 'dayjs') {
|
||||
return await this.resolve('dayjs/esm', importer, {
|
||||
skipSelf: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
// 3) 插件入口的多种写法
|
||||
// - dayjs/plugin/xxx.js -> dayjs/esm/plugin/xxx/index.js
|
||||
// - dayjs/plugin/xxx -> dayjs/esm/plugin/xxx
|
||||
const pluginWithJs = source.match(/^dayjs\/plugin\/([^/]+)\.js$/);
|
||||
if (pluginWithJs) {
|
||||
const target = `dayjs/esm/plugin/${pluginWithJs[1]}/index.js`;
|
||||
return await this.resolve(target, importer, {
|
||||
skipSelf: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
const pluginBare = source.match(/^dayjs\/plugin\/([^/]+)$/);
|
||||
if (pluginBare) {
|
||||
const target = `dayjs/esm/plugin/${pluginBare[1]}`;
|
||||
return await this.resolve(target, importer, {
|
||||
skipSelf: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
// 4) 处理多语言包
|
||||
// - dayjs/locale/xxx.js -> dayjs/esm/locale/xxx.js
|
||||
const localeWithJs = source.match(/^dayjs\/locale\/([^/]+)\.js$/);
|
||||
if (localeWithJs) {
|
||||
const target = `dayjs/esm/locale/${localeWithJs[1]}.js`;
|
||||
return await this.resolve(target, importer, {
|
||||
skipSelf: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
const localeBare = source.match(/^dayjs\/locale\/([^/]+)$/);
|
||||
if (localeBare) {
|
||||
const target = `dayjs/esm/locale/${localeBare[1]}`;
|
||||
return await this.resolve(target, importer, {
|
||||
skipSelf: true,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
config() {
|
||||
return {
|
||||
optimizeDeps: {
|
||||
exclude: ['dayjs'],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
export { viteDayjsPlugin };
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import {
|
||||
colors,
|
||||
generatorContentHash,
|
||||
readPackageJSON,
|
||||
} from '@vben/node-utils';
|
||||
|
||||
import { loadEnv } from '../utils/env';
|
||||
|
||||
interface PluginOptions {
|
||||
isBuild: boolean;
|
||||
root: string;
|
||||
}
|
||||
|
||||
const GLOBAL_CONFIG_FILE_NAME = '_app-config';
|
||||
const VBEN_ADMIN_PRO_APP_CONF = '_VBEN_ADMIN_PRO_APP_CONF_';
|
||||
|
||||
/**
|
||||
* 用于将配置文件抽离出来并注入到项目中
|
||||
* @returns
|
||||
*/
|
||||
|
||||
async function viteExtraAppConfigPlugin({
|
||||
isBuild,
|
||||
root,
|
||||
}: PluginOptions): Promise<PluginOption | undefined> {
|
||||
let publicPath: string;
|
||||
let source: string;
|
||||
let hash: string;
|
||||
|
||||
if (!isBuild) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { version = '' } = await readPackageJSON(root);
|
||||
|
||||
return {
|
||||
async configResolved(config) {
|
||||
publicPath = ensureTrailingSlash(config.base);
|
||||
source = await getConfigSource();
|
||||
hash = generatorContentHash(source, 8);
|
||||
},
|
||||
async generateBundle() {
|
||||
try {
|
||||
this.emitFile({
|
||||
fileName: `${GLOBAL_CONFIG_FILE_NAME}-${version}-${hash}.js`,
|
||||
source,
|
||||
type: 'asset',
|
||||
});
|
||||
|
||||
console.log(colors.cyan(`✨configuration file is build successfully!`));
|
||||
} catch (error) {
|
||||
console.log(
|
||||
colors.red(
|
||||
`configuration file configuration file failed to package:\n${error}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
name: 'vite:extra-app-config',
|
||||
async transformIndexHtml(html) {
|
||||
const appConfigSrc = `${publicPath}${GLOBAL_CONFIG_FILE_NAME}-${version}-${hash}.js`;
|
||||
|
||||
return {
|
||||
html,
|
||||
tags: [{ attrs: { src: appConfigSrc }, tag: 'script' }],
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function getConfigSource() {
|
||||
const config = await loadEnv();
|
||||
const windowVariable = `window.${VBEN_ADMIN_PRO_APP_CONF}`;
|
||||
// 确保变量不会被修改
|
||||
let source = `${windowVariable}=${JSON.stringify(config)};`;
|
||||
source += `
|
||||
Object.freeze(${windowVariable});
|
||||
Object.defineProperty(window, "${VBEN_ADMIN_PRO_APP_CONF}", {
|
||||
configurable: false,
|
||||
writable: false,
|
||||
});
|
||||
`.replaceAll(/\s/g, '');
|
||||
return source;
|
||||
}
|
||||
|
||||
function ensureTrailingSlash(path: string) {
|
||||
return path.endsWith('/') ? path : `${path}/`;
|
||||
}
|
||||
|
||||
export { viteExtraAppConfigPlugin };
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
FORM_FIELD_SLOT_MIGRATION_WARNING,
|
||||
viteFormFieldSlotMigrationWarningPlugin,
|
||||
} from './form-field-slot-migration-warning';
|
||||
|
||||
describe('form field slot migration warning plugin', () => {
|
||||
it('warns in serve mode and injects the same browser message', () => {
|
||||
const plugin = viteFormFieldSlotMigrationWarningPlugin();
|
||||
const warning = vi.fn();
|
||||
|
||||
expect(plugin.apply).toBe('serve');
|
||||
expect(plugin.configResolved).toBeTypeOf('function');
|
||||
if (typeof plugin.configResolved !== 'function') return;
|
||||
|
||||
plugin.configResolved({ logger: { warn: warning } } as ResolvedConfig);
|
||||
|
||||
expect(warning).toHaveBeenCalledOnce();
|
||||
expect(warning).toHaveBeenCalledWith(FORM_FIELD_SLOT_MIGRATION_WARNING);
|
||||
expect(plugin.transformIndexHtml).toBeTypeOf('function');
|
||||
if (typeof plugin.transformIndexHtml !== 'function') return;
|
||||
|
||||
const result = plugin.transformIndexHtml('', {} as never);
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
attrs: {
|
||||
'data-vben-form-field-slot-migration-warning': '',
|
||||
},
|
||||
children: `console.warn(${JSON.stringify(FORM_FIELD_SLOT_MIGRATION_WARNING)});`,
|
||||
injectTo: 'body',
|
||||
tag: 'script',
|
||||
},
|
||||
]);
|
||||
expect(FORM_FIELD_SLOT_MIGRATION_WARNING).toContain('`v-bind="slotProps"`');
|
||||
expect(FORM_FIELD_SLOT_MIGRATION_WARNING).toContain(
|
||||
'`v-bind="slotProps.componentProps"`',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Plugin } from 'vite';
|
||||
|
||||
const FORM_FIELD_SLOT_MIGRATION_WARNING =
|
||||
'[Vben Form] BREAKING CHANGE: Named field slot control bindings moved to `slotProps.componentProps`. Replace `v-bind="slotProps"` with `v-bind="slotProps.componentProps"`. See https://doc.vben.pro/components/common-ui/vben-form.html';
|
||||
|
||||
function viteFormFieldSlotMigrationWarningPlugin(): Plugin {
|
||||
return {
|
||||
apply: 'serve',
|
||||
configResolved(config) {
|
||||
config.logger.warn(FORM_FIELD_SLOT_MIGRATION_WARNING);
|
||||
},
|
||||
name: 'vite:form-field-slot-migration-warning',
|
||||
transformIndexHtml() {
|
||||
return [
|
||||
{
|
||||
attrs: {
|
||||
'data-vben-form-field-slot-migration-warning': '',
|
||||
},
|
||||
children: `console.warn(${JSON.stringify(FORM_FIELD_SLOT_MIGRATION_WARNING)});`,
|
||||
injectTo: 'body',
|
||||
tag: 'script',
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
FORM_FIELD_SLOT_MIGRATION_WARNING,
|
||||
viteFormFieldSlotMigrationWarningPlugin,
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { Options as HtmlMinifierOptions } from 'html-minifier-terser';
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import { minify } from 'html-minifier-terser';
|
||||
|
||||
const HTML_MINIFY_OPTIONS = {
|
||||
collapseWhitespace: true,
|
||||
minifyCSS: true,
|
||||
minifyJS: true,
|
||||
removeComments: true,
|
||||
removeRedundantAttributes: true,
|
||||
removeScriptTypeAttributes: true,
|
||||
removeStyleLinkTypeAttributes: true,
|
||||
useShortDoctype: true,
|
||||
} as const;
|
||||
|
||||
function viteHtmlPlugin(options: HtmlMinifierOptions = {}): PluginOption {
|
||||
return {
|
||||
name: 'vben-native-html',
|
||||
transformIndexHtml: {
|
||||
order: 'post',
|
||||
async handler(html, ctx) {
|
||||
if (!ctx.bundle) {
|
||||
return html;
|
||||
}
|
||||
return await minify(html, {
|
||||
...HTML_MINIFY_OPTIONS,
|
||||
...options,
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export { viteHtmlPlugin };
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* 参考 https://github.com/jspm/vite-plugin-jspm,调整为需要的功能
|
||||
*/
|
||||
import type { GeneratorOptions } from '@jspm/generator';
|
||||
import type { Plugin } from 'vite';
|
||||
|
||||
import { Generator } from '@jspm/generator';
|
||||
import { load } from 'cheerio';
|
||||
import { minify } from 'html-minifier-terser';
|
||||
|
||||
const DEFAULT_PROVIDER = 'jspm.io';
|
||||
|
||||
type pluginOptions = GeneratorOptions & {
|
||||
debug?: boolean;
|
||||
defaultProvider?: 'esm.sh' | 'jsdelivr' | 'jspm.io';
|
||||
importmap?: Array<{ name: string; range?: string }>;
|
||||
};
|
||||
|
||||
// async function getLatestVersionOfShims() {
|
||||
// const result = await fetch('https://ga.jspm.io/npm:es-module-shims');
|
||||
// const version = result.text();
|
||||
// return version;
|
||||
// }
|
||||
|
||||
async function getShimsUrl(provide: string) {
|
||||
// const version = await getLatestVersionOfShims();
|
||||
const version = '1.10.0';
|
||||
|
||||
const shimsSubpath = `dist/es-module-shims.js`;
|
||||
const providerShimsMap: Record<string, string> = {
|
||||
'esm.sh': `https://esm.sh/es-module-shims@${version}/${shimsSubpath}`,
|
||||
// unpkg: `https://unpkg.com/es-module-shims@${version}/${shimsSubpath}`,
|
||||
jsdelivr: `https://cdn.jsdelivr.net/npm/es-module-shims@${version}/${shimsSubpath}`,
|
||||
|
||||
// 下面两个CDN不稳定,暂时不用
|
||||
'jspm.io': `https://ga.jspm.io/npm:es-module-shims@${version}/${shimsSubpath}`,
|
||||
};
|
||||
|
||||
return providerShimsMap[provide] || providerShimsMap[DEFAULT_PROVIDER];
|
||||
}
|
||||
|
||||
let generator: Generator;
|
||||
|
||||
async function viteImportMapPlugin(
|
||||
pluginOptions?: pluginOptions,
|
||||
): Promise<Plugin[]> {
|
||||
const { importmap } = pluginOptions || {};
|
||||
|
||||
let isSSR = false;
|
||||
let isBuild = false;
|
||||
let installed = false;
|
||||
let installError: Error | null = null;
|
||||
|
||||
const options: pluginOptions = Object.assign(
|
||||
{},
|
||||
{
|
||||
debug: false,
|
||||
defaultProvider: 'jspm.io',
|
||||
env: ['production', 'browser', 'module'],
|
||||
importmap: [],
|
||||
},
|
||||
pluginOptions,
|
||||
);
|
||||
|
||||
generator = new Generator({
|
||||
...options,
|
||||
baseUrl: process.cwd(),
|
||||
});
|
||||
|
||||
if (options?.debug) {
|
||||
(async () => {
|
||||
for await (const { message, type } of generator.logStream()) {
|
||||
console.log(`${type}: ${message}`);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
const imports = options.inputMap?.imports ?? {};
|
||||
const scopes = options.inputMap?.scopes ?? {};
|
||||
const firstLayerKeys = Object.keys(scopes);
|
||||
const inputMapScopes: string[] = [];
|
||||
firstLayerKeys.forEach((key) => {
|
||||
inputMapScopes.push(...Object.keys(scopes[key] || {}));
|
||||
});
|
||||
const inputMapImports = Object.keys(imports);
|
||||
|
||||
const allDepNames: string[] = [
|
||||
...(importmap?.map((item) => item.name) || []),
|
||||
...inputMapImports,
|
||||
...inputMapScopes,
|
||||
];
|
||||
const depNames = new Set<string>(allDepNames);
|
||||
|
||||
const installDeps = importmap?.map((item) => ({
|
||||
range: item.range,
|
||||
target: item.name,
|
||||
}));
|
||||
|
||||
return [
|
||||
{
|
||||
async config(_, { command, isSsrBuild }) {
|
||||
isBuild = command === 'build';
|
||||
isSSR = !!isSsrBuild;
|
||||
},
|
||||
enforce: 'pre',
|
||||
name: 'importmap:external',
|
||||
resolveId(id) {
|
||||
if (isSSR || !isBuild) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!depNames.has(id)) {
|
||||
return null;
|
||||
}
|
||||
return { external: true, id };
|
||||
},
|
||||
},
|
||||
{
|
||||
enforce: 'post',
|
||||
name: 'importmap:install',
|
||||
async resolveId() {
|
||||
if (isSSR || !isBuild || installed) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
installed = true;
|
||||
await Promise.allSettled(
|
||||
(installDeps || []).map((dep) => generator.install(dep)),
|
||||
);
|
||||
} catch (error: any) {
|
||||
installError = error;
|
||||
installed = false;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
{
|
||||
buildEnd() {
|
||||
// 未生成importmap时,抛出错误,防止被turbo缓存
|
||||
if (!installed && !isSSR) {
|
||||
installError && console.error(installError);
|
||||
throw new Error('Importmap installation failed.');
|
||||
}
|
||||
},
|
||||
enforce: 'post',
|
||||
name: 'importmap:html',
|
||||
transformIndexHtml: {
|
||||
async handler(html) {
|
||||
if (isSSR || !isBuild) {
|
||||
return html;
|
||||
}
|
||||
|
||||
const importmapJson = generator.getMap();
|
||||
|
||||
if (!importmapJson) {
|
||||
return html;
|
||||
}
|
||||
|
||||
const esModuleShimsSrc = await getShimsUrl(
|
||||
options.defaultProvider || DEFAULT_PROVIDER,
|
||||
);
|
||||
|
||||
const resultHtml = await injectShimsToHtml(
|
||||
html,
|
||||
esModuleShimsSrc || '',
|
||||
);
|
||||
html = await minify(resultHtml || html, {
|
||||
collapseWhitespace: true,
|
||||
minifyCSS: true,
|
||||
minifyJS: true,
|
||||
removeComments: false,
|
||||
});
|
||||
|
||||
return {
|
||||
html,
|
||||
tags: [
|
||||
{
|
||||
attrs: {
|
||||
type: 'importmap',
|
||||
},
|
||||
injectTo: 'head-prepend',
|
||||
tag: 'script',
|
||||
children: `${JSON.stringify(importmapJson)}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
order: 'post',
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async function injectShimsToHtml(html: string, esModuleShimUrl: string) {
|
||||
const $ = load(html);
|
||||
|
||||
const $script = $(`script[type='module']`);
|
||||
|
||||
if (!$script) {
|
||||
return;
|
||||
}
|
||||
|
||||
const entry = $script.attr('src');
|
||||
|
||||
$script.removeAttr('type');
|
||||
$script.removeAttr('crossorigin');
|
||||
$script.removeAttr('src');
|
||||
$script.html(`
|
||||
if (!HTMLScriptElement.supports || !HTMLScriptElement.supports('importmap')) {
|
||||
self.importShim = function () {
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
document.head.appendChild(
|
||||
Object.assign(document.createElement('script'), {
|
||||
src: '${esModuleShimUrl}',
|
||||
crossorigin: 'anonymous',
|
||||
async: true,
|
||||
onload() {
|
||||
if (!importShim.$proxy) {
|
||||
resolve(importShim);
|
||||
} else {
|
||||
reject(new Error('No globalThis.importShim found:' + esModuleShimUrl));
|
||||
}
|
||||
},
|
||||
onerror(error) {
|
||||
reject(error);
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
importShim.$proxy = true;
|
||||
return promise.then((importShim) => importShim(...arguments));
|
||||
};
|
||||
}
|
||||
|
||||
var modules = ['${entry}'];
|
||||
typeof importShim === 'function'
|
||||
? modules.forEach((moduleName) => importShim(moduleName))
|
||||
: modules.forEach((moduleName) => import(moduleName));
|
||||
`);
|
||||
$('body').after($script);
|
||||
$('head').remove(`script[type='module']`);
|
||||
return $.html();
|
||||
}
|
||||
|
||||
export { viteImportMapPlugin };
|
||||
@@ -0,0 +1,268 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import type {
|
||||
ApplicationPluginOptions,
|
||||
CommonPluginOptions,
|
||||
ConditionPlugin,
|
||||
LibraryPluginOptions,
|
||||
} from '../typing';
|
||||
|
||||
import viteVueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
import viteVue from '@vitejs/plugin-vue';
|
||||
import viteVueJsx from '@vitejs/plugin-vue-jsx';
|
||||
import { visualizer as viteVisualizerPlugin } from 'rollup-plugin-visualizer';
|
||||
import viteDtsPlugin from 'unplugin-dts/vite';
|
||||
import viteCompressPlugin from 'vite-plugin-compression';
|
||||
import { VitePWA } from 'vite-plugin-pwa';
|
||||
import viteVueDevTools from 'vite-plugin-vue-devtools';
|
||||
|
||||
import { viteArchiverPlugin } from './archiver';
|
||||
import { viteDayjsPlugin } from './dayjs';
|
||||
import { viteExtraAppConfigPlugin } from './extra-app-config';
|
||||
import { viteFormFieldSlotMigrationWarningPlugin } from './form-field-slot-migration-warning';
|
||||
import { viteHtmlPlugin } from './html';
|
||||
import { viteImportMapPlugin } from './importmap';
|
||||
import { viteInjectAppLoadingPlugin } from './inject-app-loading';
|
||||
import { viteMetadataPlugin } from './inject-metadata';
|
||||
import { viteLicensePlugin } from './license';
|
||||
import { viteNitroMockPlugin } from './nitro-mock';
|
||||
import { vitePrintPlugin } from './print';
|
||||
import { viteTailwindReferencePlugin } from './tailwind-reference';
|
||||
import { viteVxeTableImportsPlugin } from './vxe-table';
|
||||
|
||||
/**
|
||||
* 获取条件成立的 vite 插件
|
||||
* @param conditionPlugins
|
||||
*/
|
||||
async function loadConditionPlugins(conditionPlugins: ConditionPlugin[]) {
|
||||
const plugins: PluginOption[] = [];
|
||||
for (const conditionPlugin of conditionPlugins) {
|
||||
if (conditionPlugin.condition) {
|
||||
const realPlugins = await conditionPlugin.plugins();
|
||||
plugins.push(...realPlugins);
|
||||
}
|
||||
}
|
||||
return plugins.flat();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件获取通用的vite插件
|
||||
*/
|
||||
async function loadCommonPlugins(
|
||||
options: CommonPluginOptions,
|
||||
): Promise<ConditionPlugin[]> {
|
||||
const { devtools, injectMetadata, isBuild, visualizer } = options;
|
||||
return [
|
||||
{
|
||||
condition: true,
|
||||
plugins: () => [
|
||||
viteVue({
|
||||
script: {
|
||||
defineModel: true,
|
||||
// propsDestructure: true,
|
||||
},
|
||||
}),
|
||||
viteVueJsx(),
|
||||
viteTailwindReferencePlugin(),
|
||||
tailwindcss(),
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
condition: !isBuild && devtools,
|
||||
plugins: () => [viteVueDevTools()],
|
||||
},
|
||||
{
|
||||
condition: injectMetadata,
|
||||
plugins: async () => [await viteMetadataPlugin()],
|
||||
},
|
||||
{
|
||||
condition: isBuild && !!visualizer,
|
||||
plugins: () => [
|
||||
viteVisualizerPlugin({
|
||||
filename: './node_modules/.cache/visualizer/stats.html',
|
||||
gzipSize: true,
|
||||
open: true,
|
||||
}) as PluginOption,
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件获取应用类型的vite插件
|
||||
*/
|
||||
async function loadApplicationPlugins(
|
||||
options: ApplicationPluginOptions,
|
||||
): Promise<PluginOption[]> {
|
||||
// 单独取,否则commonOptions拿不到
|
||||
const isBuild = options.isBuild;
|
||||
const env = options.env;
|
||||
|
||||
const {
|
||||
archiver,
|
||||
archiverPluginOptions,
|
||||
compress,
|
||||
compressTypes,
|
||||
extraAppConfig,
|
||||
html,
|
||||
dayjs,
|
||||
i18n,
|
||||
importmap,
|
||||
importmapOptions,
|
||||
injectAppLoading,
|
||||
license,
|
||||
nitroMock,
|
||||
nitroMockOptions,
|
||||
print,
|
||||
printInfoMap,
|
||||
pwa,
|
||||
pwaOptions,
|
||||
vxeTableLazyImport,
|
||||
...commonOptions
|
||||
} = options;
|
||||
|
||||
const commonPlugins = await loadCommonPlugins(commonOptions);
|
||||
|
||||
return await loadConditionPlugins([
|
||||
...commonPlugins,
|
||||
{
|
||||
condition: i18n,
|
||||
plugins: async () => {
|
||||
return [
|
||||
viteVueI18nPlugin({
|
||||
compositionOnly: true,
|
||||
fullInstall: true,
|
||||
runtimeOnly: true,
|
||||
}),
|
||||
];
|
||||
},
|
||||
},
|
||||
{
|
||||
condition: print,
|
||||
plugins: async () => {
|
||||
return [await vitePrintPlugin({ infoMap: printInfoMap })];
|
||||
},
|
||||
},
|
||||
{
|
||||
condition: !isBuild,
|
||||
plugins: () => [viteFormFieldSlotMigrationWarningPlugin()],
|
||||
},
|
||||
{
|
||||
condition: vxeTableLazyImport,
|
||||
plugins: async () => {
|
||||
return [await viteVxeTableImportsPlugin()];
|
||||
},
|
||||
},
|
||||
{
|
||||
condition: nitroMock,
|
||||
plugins: async () => {
|
||||
return [await viteNitroMockPlugin(nitroMockOptions)];
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
condition: injectAppLoading,
|
||||
plugins: async () => [await viteInjectAppLoadingPlugin(!!isBuild, env)],
|
||||
},
|
||||
{
|
||||
condition: license,
|
||||
plugins: async () => [await viteLicensePlugin()],
|
||||
},
|
||||
{
|
||||
condition: pwa,
|
||||
plugins: () =>
|
||||
VitePWA({
|
||||
injectRegister: false,
|
||||
workbox: {
|
||||
globPatterns: [],
|
||||
},
|
||||
...pwaOptions,
|
||||
manifest: {
|
||||
display: 'standalone',
|
||||
start_url: '/',
|
||||
theme_color: '#ffffff',
|
||||
...pwaOptions?.manifest,
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
condition: isBuild && !!compress,
|
||||
plugins: () => {
|
||||
const compressPlugins: PluginOption[] = [];
|
||||
if (compressTypes?.includes('brotli')) {
|
||||
compressPlugins.push(
|
||||
viteCompressPlugin({ deleteOriginFile: false, ext: '.br' }),
|
||||
);
|
||||
}
|
||||
if (compressTypes?.includes('gzip')) {
|
||||
compressPlugins.push(
|
||||
viteCompressPlugin({ deleteOriginFile: false, ext: '.gz' }),
|
||||
);
|
||||
}
|
||||
return compressPlugins;
|
||||
},
|
||||
},
|
||||
{
|
||||
condition: !!html,
|
||||
plugins: () => [viteHtmlPlugin(typeof html === 'object' ? html : {})],
|
||||
},
|
||||
{
|
||||
condition: isBuild && importmap,
|
||||
plugins: () => {
|
||||
return [viteImportMapPlugin(importmapOptions)];
|
||||
},
|
||||
},
|
||||
{
|
||||
condition: isBuild && extraAppConfig,
|
||||
plugins: async () => [
|
||||
await viteExtraAppConfigPlugin({ isBuild: true, root: process.cwd() }),
|
||||
],
|
||||
},
|
||||
{
|
||||
condition: archiver,
|
||||
plugins: async () => {
|
||||
return [await viteArchiverPlugin(archiverPluginOptions)];
|
||||
},
|
||||
},
|
||||
{
|
||||
condition: dayjs,
|
||||
plugins: () => [viteDayjsPlugin()],
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据条件获取库类型的vite插件
|
||||
*/
|
||||
async function loadLibraryPlugins(
|
||||
options: LibraryPluginOptions,
|
||||
): Promise<PluginOption[]> {
|
||||
// 单独取,否则commonOptions拿不到
|
||||
const isBuild = options.isBuild;
|
||||
const { dts, ...commonOptions } = options;
|
||||
const dtsOptions = typeof dts === 'object' ? dts : undefined;
|
||||
const commonPlugins = await loadCommonPlugins(commonOptions);
|
||||
return await loadConditionPlugins([
|
||||
...commonPlugins,
|
||||
{
|
||||
condition: isBuild && !!dts,
|
||||
plugins: () => [viteDtsPlugin(dtsOptions)],
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
export { viteCssLayerPlugin } from './css-layer';
|
||||
|
||||
export {
|
||||
loadApplicationPlugins,
|
||||
loadLibraryPlugins,
|
||||
viteArchiverPlugin,
|
||||
viteCompressPlugin,
|
||||
viteDayjsPlugin,
|
||||
viteDtsPlugin,
|
||||
viteHtmlPlugin,
|
||||
viteVisualizerPlugin,
|
||||
viteVxeTableImportsPlugin,
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
# inject-app-loading
|
||||
|
||||
用于在应用加载时显示加载动画的插件,可自行选择加载动画的样式。
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
<style data-app-loading="inject-css">
|
||||
html {
|
||||
/* same as ant-design-vue/dist/reset.css setting, avoid the title line-height changed */
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.dark .loading {
|
||||
background-color: #0d0d10;
|
||||
}
|
||||
|
||||
.dark .loading .title {
|
||||
color: rgb(255 255 255 / 85%);
|
||||
}
|
||||
|
||||
.loading {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
background-color: #f4f7f9;
|
||||
}
|
||||
|
||||
.loading.hidden {
|
||||
visibility: hidden;
|
||||
opacity: 0;
|
||||
transition: all 0.6s ease-out;
|
||||
}
|
||||
|
||||
.loading .title {
|
||||
margin-top: 36px;
|
||||
font-size: 30px;
|
||||
font-weight: 600;
|
||||
color: rgb(0 0 0 / 85%);
|
||||
}
|
||||
|
||||
.dot {
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
display: inline-block;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
margin-top: 30px;
|
||||
font-size: 32px;
|
||||
transform: rotate(45deg);
|
||||
animation: rotate-ani 1.2s infinite linear;
|
||||
}
|
||||
|
||||
.dot i {
|
||||
position: absolute;
|
||||
display: block;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
background-color: hsl(var(--primary, 210 100% 50%));
|
||||
border-radius: 100%;
|
||||
opacity: 0.3;
|
||||
transform: scale(0.75);
|
||||
transform-origin: 50% 50%;
|
||||
animation: spin-move-ani 1s infinite linear alternate;
|
||||
}
|
||||
|
||||
.dot i:nth-child(1) {
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.dot i:nth-child(2) {
|
||||
top: 0;
|
||||
right: 0;
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
|
||||
.dot i:nth-child(3) {
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
animation-delay: 0.8s;
|
||||
}
|
||||
|
||||
.dot i:nth-child(4) {
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
animation-delay: 1.2s;
|
||||
}
|
||||
|
||||
@keyframes rotate-ani {
|
||||
to {
|
||||
transform: rotate(405deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes spin-move-ani {
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<div class="loading" id="__app-loading__">
|
||||
<span class="dot"><i></i><i></i><i></i><i></i></span>
|
||||
<div class="title">%VITE_APP_TITLE%</div>
|
||||
</div>
|
||||
@@ -0,0 +1,113 @@
|
||||
<style data-app-loading="inject-css">
|
||||
html {
|
||||
/* same as ant-design-vue/dist/reset.css setting, avoid the title line-height changed */
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.loading {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background-color: #f4f7f9;
|
||||
|
||||
/* transition: all 0.8s ease-out; */
|
||||
}
|
||||
|
||||
.loading.hidden {
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
transition: all 0.8s ease-out;
|
||||
}
|
||||
|
||||
.dark .loading {
|
||||
background: #0d0d10;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin-top: 66px;
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
color: rgb(0 0 0 / 85%);
|
||||
}
|
||||
|
||||
.dark .title {
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.loader {
|
||||
position: relative;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
|
||||
.loader::before {
|
||||
position: absolute;
|
||||
top: 60px;
|
||||
left: 0;
|
||||
width: 48px;
|
||||
height: 5px;
|
||||
content: '';
|
||||
background: hsl(var(--primary, 210 100% 50%) / 50%);
|
||||
border-radius: 50%;
|
||||
animation: shadow-ani 0.5s linear infinite;
|
||||
}
|
||||
|
||||
.loader::after {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
content: '';
|
||||
background: hsl(var(--primary, 210 100% 50%));
|
||||
border-radius: 4px;
|
||||
animation: jump-ani 0.5s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes jump-ani {
|
||||
15% {
|
||||
border-bottom-right-radius: 3px;
|
||||
}
|
||||
|
||||
25% {
|
||||
transform: translateY(9px) rotate(22.5deg);
|
||||
}
|
||||
|
||||
50% {
|
||||
border-bottom-right-radius: 40px;
|
||||
transform: translateY(18px) scale(1, 0.9) rotate(45deg);
|
||||
}
|
||||
|
||||
75% {
|
||||
transform: translateY(9px) rotate(67.5deg);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: translateY(0) rotate(90deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes shadow-ani {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(1, 1);
|
||||
}
|
||||
|
||||
50% {
|
||||
transform: scale(1.2, 1);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<div class="loading" id="__app-loading__">
|
||||
<div class="loader"></div>
|
||||
<div class="title">%VITE_APP_TITLE%</div>
|
||||
</div>
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import fsp from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { readPackageJSON } from '@vben/node-utils';
|
||||
|
||||
/**
|
||||
* 用于生成将loading样式注入到项目中
|
||||
* 为多app提供loading样式,无需在每个 app -> index.html单独引入
|
||||
*/
|
||||
async function viteInjectAppLoadingPlugin(
|
||||
isBuild: boolean,
|
||||
env: Record<string, any> = {},
|
||||
loadingTemplate = 'loading.html',
|
||||
): Promise<PluginOption | undefined> {
|
||||
const loadingHtml = await getLoadingRawByHtmlTemplate(loadingTemplate);
|
||||
const { version } = await readPackageJSON(process.cwd());
|
||||
const envRaw = isBuild ? 'prod' : 'dev';
|
||||
const cacheName = `'${env.VITE_APP_NAMESPACE}-${version}-${envRaw}-preferences-theme'`;
|
||||
|
||||
// 获取缓存的主题
|
||||
// 保证黑暗主题下,刷新页面时,loading也是黑暗主题
|
||||
const injectScript = `
|
||||
<script data-app-loading="inject-js">
|
||||
var theme = localStorage.getItem(${cacheName});
|
||||
document.documentElement.classList.toggle('dark', /dark/.test(theme));
|
||||
</script>
|
||||
`;
|
||||
|
||||
if (!loadingHtml) {
|
||||
return;
|
||||
}
|
||||
|
||||
return {
|
||||
enforce: 'pre',
|
||||
name: 'vite:inject-app-loading',
|
||||
transformIndexHtml: {
|
||||
handler(html) {
|
||||
const re = /<body\s*>/;
|
||||
html = html.replace(re, `<body>${injectScript}${loadingHtml}`);
|
||||
return html;
|
||||
},
|
||||
order: 'pre',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于获取loading的html模板
|
||||
*/
|
||||
async function getLoadingRawByHtmlTemplate(loadingTemplate: string) {
|
||||
// 支持在app内自定义loading模板,模版参考default-loading.html即可
|
||||
let appLoadingPath = join(process.cwd(), loadingTemplate);
|
||||
|
||||
if (!fs.existsSync(appLoadingPath)) {
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||
appLoadingPath = join(__dirname, './default-loading.html');
|
||||
}
|
||||
|
||||
return await fsp.readFile(appLoadingPath, 'utf8');
|
||||
}
|
||||
|
||||
export { viteInjectAppLoadingPlugin };
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import {
|
||||
dateUtil,
|
||||
findMonorepoRoot,
|
||||
getPackages,
|
||||
readPackageJSON,
|
||||
} from '@vben/node-utils';
|
||||
|
||||
import { readWorkspaceManifest } from '@pnpm/workspace.read-manifest';
|
||||
|
||||
function resolvePackageVersion(
|
||||
pkgsMeta: Record<string, string>,
|
||||
name: string,
|
||||
value: string,
|
||||
catalog: Record<string, string>,
|
||||
) {
|
||||
if (value.includes('catalog:')) {
|
||||
return catalog[name];
|
||||
}
|
||||
|
||||
if (value.includes('workspace')) {
|
||||
return pkgsMeta[name];
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
async function resolveMonorepoDependencies() {
|
||||
const { packages } = await getPackages();
|
||||
const manifest = await readWorkspaceManifest(findMonorepoRoot());
|
||||
const catalog = manifest?.catalog || {};
|
||||
|
||||
const resultDevDependencies: Record<string, string | undefined> = {};
|
||||
const resultDependencies: Record<string, string | undefined> = {};
|
||||
const pkgsMeta: Record<string, string> = {};
|
||||
|
||||
for (const { packageJson } of packages) {
|
||||
pkgsMeta[packageJson.name] = packageJson.version;
|
||||
}
|
||||
|
||||
for (const { packageJson } of packages) {
|
||||
const { dependencies = {}, devDependencies = {} } = packageJson;
|
||||
for (const [key, value] of Object.entries(dependencies)) {
|
||||
resultDependencies[key] = resolvePackageVersion(
|
||||
pkgsMeta,
|
||||
key,
|
||||
value,
|
||||
catalog,
|
||||
);
|
||||
}
|
||||
for (const [key, value] of Object.entries(devDependencies)) {
|
||||
resultDevDependencies[key] = resolvePackageVersion(
|
||||
pkgsMeta,
|
||||
key,
|
||||
value,
|
||||
catalog,
|
||||
);
|
||||
}
|
||||
}
|
||||
return {
|
||||
dependencies: resultDependencies,
|
||||
devDependencies: resultDevDependencies,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 用于注入项目信息
|
||||
*/
|
||||
async function viteMetadataPlugin(
|
||||
root = process.cwd(),
|
||||
): Promise<PluginOption | undefined> {
|
||||
const { author, description, homepage, license, version } =
|
||||
await readPackageJSON(root);
|
||||
|
||||
const buildTime = dateUtil().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
return {
|
||||
async config() {
|
||||
const { dependencies, devDependencies } =
|
||||
await resolveMonorepoDependencies();
|
||||
|
||||
const isAuthorObject = typeof author === 'object';
|
||||
const authorName = isAuthorObject ? author.name : author;
|
||||
const authorEmail = isAuthorObject ? author.email : null;
|
||||
const authorUrl = isAuthorObject ? author.url : null;
|
||||
|
||||
return {
|
||||
define: {
|
||||
__VBEN_ADMIN_METADATA__: JSON.stringify({
|
||||
authorEmail,
|
||||
authorName,
|
||||
authorUrl,
|
||||
buildTime,
|
||||
dependencies,
|
||||
description,
|
||||
devDependencies,
|
||||
homepage,
|
||||
license,
|
||||
version,
|
||||
}),
|
||||
'import.meta.env.VITE_APP_VERSION': JSON.stringify(version),
|
||||
},
|
||||
};
|
||||
},
|
||||
enforce: 'post',
|
||||
name: 'vite:inject-metadata',
|
||||
};
|
||||
}
|
||||
|
||||
export { viteMetadataPlugin };
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import { EOL } from 'node:os';
|
||||
|
||||
import { dateUtil, readPackageJSON } from '@vben/node-utils';
|
||||
|
||||
/**
|
||||
* 用于注入版权信息
|
||||
* @returns
|
||||
*/
|
||||
async function viteLicensePlugin(
|
||||
root = process.cwd(),
|
||||
): Promise<PluginOption | undefined> {
|
||||
const {
|
||||
description = '',
|
||||
homepage = '',
|
||||
version = '',
|
||||
} = await readPackageJSON(root);
|
||||
|
||||
return {
|
||||
apply: 'build',
|
||||
enforce: 'post',
|
||||
generateBundle: {
|
||||
handler(_options, bundle) {
|
||||
const date = dateUtil().format('YYYY-MM-DD ');
|
||||
const copyrightText = `/*!
|
||||
* Vben Admin
|
||||
* Version: ${version}
|
||||
* Author: vben
|
||||
* Copyright (C) 2024 Vben
|
||||
* License: MIT License
|
||||
* Description: ${description}
|
||||
* Date Created: ${date}
|
||||
* Homepage: ${homepage}
|
||||
* Contact: ann.vben@gmail.com
|
||||
*/
|
||||
`.trim();
|
||||
|
||||
for (const [, fileContent] of Object.entries(bundle)) {
|
||||
if (fileContent.type === 'chunk' && fileContent.isEntry) {
|
||||
// 插入版权信息
|
||||
const content = fileContent.code;
|
||||
const updatedContent = `${copyrightText}${EOL}${content}`;
|
||||
// 更新bundle
|
||||
fileContent.code = updatedContent;
|
||||
}
|
||||
}
|
||||
},
|
||||
order: 'post',
|
||||
},
|
||||
name: 'vite:license',
|
||||
};
|
||||
}
|
||||
|
||||
export { viteLicensePlugin };
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import type { NitroMockPluginOptions } from '../typing';
|
||||
|
||||
import { colors, consola, getPackage } from '@vben/node-utils';
|
||||
|
||||
import getPort from 'get-port';
|
||||
import { build, createDevServer, createNitro, prepare } from 'nitropack';
|
||||
|
||||
const hmrKeyRe = /^runtimeConfig\.|routeRules\./;
|
||||
|
||||
export const viteNitroMockPlugin = ({
|
||||
mockServerPackage = '@vben/backend-mock',
|
||||
port = 5320,
|
||||
verbose = true,
|
||||
}: NitroMockPluginOptions = {}): PluginOption => {
|
||||
return {
|
||||
async configureServer(server) {
|
||||
const availablePort = await getPort({ port });
|
||||
if (availablePort !== port) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pkg = await getPackage(mockServerPackage);
|
||||
if (!pkg) {
|
||||
consola.log(
|
||||
`Package ${mockServerPackage} not found. Skip mock server.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
runNitroServer(pkg.dir, port, verbose);
|
||||
|
||||
const _printUrls = server.printUrls;
|
||||
server.printUrls = () => {
|
||||
_printUrls();
|
||||
|
||||
consola.log(
|
||||
` ${colors.green('➜')} ${colors.bold('Nitro Mock Server')}: ${colors.cyan(`http://localhost:${port}/api`)}`,
|
||||
);
|
||||
};
|
||||
},
|
||||
enforce: 'pre',
|
||||
name: 'vite:mock-server',
|
||||
};
|
||||
};
|
||||
|
||||
async function runNitroServer(rootDir: string, port: number, verbose: boolean) {
|
||||
let nitro: any;
|
||||
const reload = async () => {
|
||||
if (nitro) {
|
||||
consola.info('Restarting dev server...');
|
||||
if ('unwatch' in nitro.options._c12) {
|
||||
await nitro.options._c12.unwatch();
|
||||
}
|
||||
await nitro.close();
|
||||
}
|
||||
nitro = await createNitro(
|
||||
{
|
||||
dev: true,
|
||||
preset: 'nitro-dev',
|
||||
rootDir,
|
||||
},
|
||||
{
|
||||
c12: {
|
||||
async onUpdate({ getDiff, newConfig }) {
|
||||
const diff = getDiff();
|
||||
if (diff.length === 0) {
|
||||
return;
|
||||
}
|
||||
verbose &&
|
||||
consola.info(
|
||||
`Nitro config updated:\n${diff
|
||||
.map((entry) => ` ${entry.toString()}`)
|
||||
.join('\n')}`,
|
||||
);
|
||||
await (diff.every((e) => hmrKeyRe.test(e.key))
|
||||
? nitro.updateConfig(newConfig.config)
|
||||
: reload());
|
||||
},
|
||||
},
|
||||
watch: true,
|
||||
},
|
||||
);
|
||||
nitro.hooks.hookOnce('restart', reload);
|
||||
|
||||
const server = createDevServer(nitro);
|
||||
await server.listen(port, { showURL: false });
|
||||
await prepare(nitro);
|
||||
await build(nitro);
|
||||
|
||||
if (verbose) {
|
||||
console.log('');
|
||||
consola.success(colors.bold(colors.green('Nitro Mock Server started.')));
|
||||
}
|
||||
};
|
||||
return await reload();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import type { PrintPluginOptions } from '../typing';
|
||||
|
||||
import { colors } from '@vben/node-utils';
|
||||
|
||||
export const vitePrintPlugin = (
|
||||
options: PrintPluginOptions = {},
|
||||
): PluginOption => {
|
||||
const { infoMap = {} } = options;
|
||||
|
||||
return {
|
||||
configureServer(server) {
|
||||
const _printUrls = server.printUrls;
|
||||
server.printUrls = () => {
|
||||
_printUrls();
|
||||
|
||||
for (const [key, value] of Object.entries(infoMap)) {
|
||||
console.log(
|
||||
` ${colors.green('➜')} ${colors.bold(key)}: ${colors.cyan(value)}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
},
|
||||
enforce: 'pre',
|
||||
name: 'vite:print-info',
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Plugin } from 'vite';
|
||||
|
||||
const REFERENCE_LINE = '@reference "@vben/tailwind-config/theme";\n';
|
||||
|
||||
/**
|
||||
* Auto-inject @reference into Vue SFC <style> blocks that use @apply.
|
||||
*
|
||||
* In Tailwind CSS v4, each Vue SFC <style scoped> block is processed as an
|
||||
* independent CSS module. If a style block uses @apply with custom theme
|
||||
* utilities (e.g. bg-primary, text-foreground), it needs access to the
|
||||
* @theme definition via @reference. This plugin auto-injects it so
|
||||
* individual components don't need to add it manually.
|
||||
*/
|
||||
export function viteTailwindReferencePlugin(): Plugin {
|
||||
return {
|
||||
enforce: 'pre',
|
||||
name: 'vite:tailwind-reference',
|
||||
transform(code, id) {
|
||||
// Only process Vue SFC style blocks
|
||||
if (!id.includes('.vue')) {
|
||||
return null;
|
||||
}
|
||||
if (!id.includes('type=style')) {
|
||||
return null;
|
||||
}
|
||||
// Skip if already has @reference
|
||||
if (code.includes('@reference')) {
|
||||
return null;
|
||||
}
|
||||
// Only inject if the style block uses @apply
|
||||
if (!code.includes('@apply')) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
code: REFERENCE_LINE + code,
|
||||
map: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { PluginOption } from 'vite';
|
||||
|
||||
import { lazyImport, VxeResolver } from 'vite-plugin-lazy-import';
|
||||
|
||||
async function viteVxeTableImportsPlugin(): Promise<PluginOption> {
|
||||
return [
|
||||
lazyImport({
|
||||
resolvers: [
|
||||
VxeResolver({
|
||||
libraryName: 'vxe-table',
|
||||
}),
|
||||
VxeResolver({
|
||||
libraryName: 'vxe-pc-ui',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
export { viteVxeTableImportsPlugin };
|
||||
Reference in New Issue
Block a user