Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use unplugin-config #3106

Merged
merged 2 commits into from
Oct 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions internal/vite-config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"rollup-plugin-visualizer": "^5.9.2",
"sass": "^1.63.6",
"unocss": "^0.53.4",
"unplugin-config": "^0.0.13",
"vite-plugin-compression": "^0.5.1",
"vite-plugin-dts": "^3.1.0",
"vite-plugin-html": "^3.2.0",
Expand Down
113 changes: 15 additions & 98 deletions internal/vite-config/src/plugins/appConfig.ts
Original file line number Diff line number Diff line change
@@ -1,104 +1,21 @@
import colors from 'picocolors';
import { readPackageJSON } from 'pkg-types';
import GenerateConfig from 'unplugin-config/vite';
import { type PluginOption } from 'vite';

import { getEnvConfig } from '../utils/env';
import { createContentHash } from '../utils/hash';
import { strToHex } from '../utils/hash';

const GLOBAL_CONFIG_FILE_NAME = '_app.config.js';
const PLUGIN_NAME = 'app-config';

async function createAppConfigPlugin({
root,
isBuild,
}: {
root: string;
isBuild: boolean;
}): Promise<PluginOption> {
let publicPath: string;
let source: string;
if (!isBuild) {
return {
name: PLUGIN_NAME,
};
}
const { version = '' } = await readPackageJSON(root);

return {
name: PLUGIN_NAME,
async configResolved(_config) {
const appTitle = _config?.env?.VITE_GLOB_APP_TITLE ?? '';
// appTitle = appTitle.replace(/\s/g, '_').replace(/-/g, '_');
publicPath = _config.base;
source = await getConfigSource(appTitle);
},
async transformIndexHtml(html) {
publicPath = publicPath.endsWith('/') ? publicPath : `${publicPath}/`;

const appConfigSrc = `${
publicPath || '/'
}${GLOBAL_CONFIG_FILE_NAME}?v=${version}-${createContentHash(source)}`;

return {
html,
tags: [
{
tag: 'script',
attrs: {
src: appConfigSrc,
},
},
],
};
},
async generateBundle() {
try {
this.emitFile({
type: 'asset',
fileName: GLOBAL_CONFIG_FILE_NAME,
source,
});

console.log(colors.cyan(`✨configuration file is build successfully!`));
} catch (error) {
console.log(
colors.red('configuration file configuration file failed to package:\n' + error),
);
}
},
};
// This constant sets the output directory for the Vite package
const OUTPUT_DIR = 'dist';
const config: any = getEnvConfig().then();
const APP_NAME = strToHex(config?.VITE_GLOB_APP_TITLE ?? 'Vben Admin');
export function createConfigPluginConfig(shouldGenerateConfig: boolean): PluginOption {
// https://github.com/kirklin/unplugin-config
return GenerateConfig({
disabledConfig: !shouldGenerateConfig,
globConfigFileName: GLOBAL_CONFIG_FILE_NAME,
outputDir: OUTPUT_DIR,
appName: APP_NAME,
envConfigPrefix: 'VITE_GLOB_',
});
}

/**
* Get the configuration file variable name
* @param env
*/
const getVariableName = (title: string) => {
function strToHex(str: string) {
const result: string[] = [];
for (let i = 0; i < str.length; ++i) {
const hex = str.charCodeAt(i).toString(16);
result.push(('000' + hex).slice(-4));
}
return result.join('').toUpperCase();
}
return `__PRODUCTION__${strToHex(title) || '__APP'}__CONF__`.toUpperCase().replace(/\s/g, '');
};

async function getConfigSource(appTitle: string) {
const config = await getEnvConfig();
const variableName = getVariableName(appTitle);
const windowVariable = `window.${variableName}`;
// Ensure that the variable will not be modified
let source = `${windowVariable}=${JSON.stringify(config)};`;
source += `
Object.freeze(${windowVariable});
Object.defineProperty(window, "${variableName}", {
configurable: false,
writable: false,
});
`.replace(/\s/g, '');
return source;
}

export { createAppConfigPlugin };
6 changes: 3 additions & 3 deletions internal/vite-config/src/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import vueJsx from '@vitejs/plugin-vue-jsx';
import { type PluginOption } from 'vite';
import purgeIcons from 'vite-plugin-purge-icons';

import { createAppConfigPlugin } from './appConfig';
import { createConfigPluginConfig } from './appConfig';
import { configCompressPlugin } from './compress';
import { configHtmlPlugin } from './html';
import { configMockPlugin } from './mock';
Expand All @@ -18,10 +18,10 @@ interface Options {
enableAnalyze?: boolean;
}

async function createPlugins({ isBuild, root, enableMock, compress, enableAnalyze }: Options) {
async function createPlugins({ isBuild, enableMock, compress, enableAnalyze }: Options) {
const vitePlugins: (PluginOption | PluginOption[])[] = [vue(), vueJsx()];

const appConfigPlugin = await createAppConfigPlugin({ root, isBuild });
const appConfigPlugin = await createConfigPluginConfig(isBuild);
vitePlugins.push(appConfigPlugin);

// vite-plugin-html
Expand Down
10 changes: 9 additions & 1 deletion internal/vite-config/src/utils/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,13 @@ function createContentHash(content: string, hashLSize = 12) {
const hash = createHash('sha256').update(content);
return hash.digest('hex').slice(0, hashLSize);
}
function strToHex(str: string) {
const result: string[] = [];
for (let i = 0; i < str.length; ++i) {
const hex = str.charCodeAt(i).toString(16);
result.push(('000' + hex).slice(-4));
}
return result.join('').toUpperCase();
}

export { createContentHash };
export { createContentHash, strToHex };
54 changes: 54 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.