Files
xj-screen/vite.config.ts
T

94 lines
2.6 KiB
TypeScript

import { defineConfig, ConfigEnv, Plugin } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import vueJsx from '@vitejs/plugin-vue-jsx';
import postcssPluginPx2rem from 'postcss-plugin-px2rem';
import resolveExternalsPlugin from 'vite-plugin-resolve-externals';
function pathResolve(dir: string) {
return resolve(process.cwd(), '.', dir);
}
const px2remOptions = {
remUnit: 14,
rootValue: 17,
unitPrecision: 5,
mediaQuery: false,
minPixelValue: 2,
};
// 👉 定义插件(更健壮)
const injectAppEnvPlugin = (): Plugin => {
let isProduction = false;
return {
name: 'inject-app-env',
config(config, { mode }) {
isProduction = mode === 'production';
},
transformIndexHtml: (html) => {
// 确保 html 是字符串
if (typeof html !== 'string') {
console.warn('transformIndexHtml received non-string HTML');
return html;
}
if (!isProduction) {
return html; // 开发环境不注入
}
// 使用单行 script,避免换行问题
const script = `<script>window.__APP_ENV__ = { VITE_GLOB_API_URL: '__VITE_GLOB_API_URL__' };</script>`;
// 插入到 </head> 前
return html.replace('</head>', `${script}</head>`);
},
};
};
// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv) => {
return {
plugins: [
vue(),
resolveExternalsPlugin({
AMap: 'AMap',
}),
vueJsx(),
injectAppEnvPlugin(), // 使用函数式插件
],
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
postcss: {
plugins: [postcssPluginPx2rem(px2remOptions)],
},
},
resolve: {
alias: [
{
find: /\/@\//,
replacement: pathResolve('src') + '/',
},
],
extensions: ['.js', '.ts', '.mjs', '.vue', '.json', '.less', '.css'],
},
server: {
host: true,
https: false,
},
optimizeDeps: {
esbuildOptions: {
target: 'esnext',
},
include: ['lodash-es', 'ant-design-vue/es/locale/zh_CN', 'ant-design-vue/es/locale/en_US'],
},
build: {
target: 'esnext',
sourcemap: false,
},
};
});