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

Vite 构建工具配置指南 #12

Open
bouquetrender opened this issue Apr 16, 2023 · 0 comments
Open

Vite 构建工具配置指南 #12

bouquetrender opened this issue Apr 16, 2023 · 0 comments
Labels

Comments

@bouquetrender
Copy link
Owner

bouquetrender commented Apr 16, 2023

Vite 构建工具基于浏览器原生 ES 模块解析规则,利用了现代浏览器的特性,实现无需打包即可快速启动开发服务器,并支持开箱即用的 TypeScript、Vue 单文件组件等。Vite 不需要像 webpack 那样先将所有文件打包成一个或多个 bundle,然后再运行应用程序。相反 Vite 会在浏览器中使用原生的 ES 模块加载器来加载模块。

这是一份我在 React 项目中常用的 vite.config.js 配置代码,为了较好阅读添加了注释,包含了许多通用配置仅供参考。

import { defineConfig } from "vite";
import path from "path";

import react from "@vitejs/plugin-react-swc";
import checker from "vite-plugin-checker";
import { compression } from "vite-plugin-compression2";
import { createHtmlPlugin } from "vite-plugin-html";
import svgr from "vite-plugin-svgr";

import LessPluginImportNodeModules from "less-plugin-import-node-modules";
import fs from "fs";
import { comlink } from "vite-plugin-comlink";

import autoprefixer from "autoprefixer";

// 代理配置
const API_TARGET = "https://10.28.100.149";
// 代理的请求api 前缀路径
const requestProxy = ["/api"];

const VITE_APP_NAME = "system";
const DEV_HOST = "localhost";
const DEV_PORT = 8019;
const isProd = process.env.NODE_ENV === "production";

const proxy = {};
requestProxy.forEach((v) => {
	proxy[v] = {
		target: API_TARGET,
		changeOrigin: true,
		secure: false,
	};
});

export default defineConfig({
	// 基础路径
	base: `/${VITE_APP_NAME}/`,

	// 插件
	plugins: [
		// 只在生产环境引入 plugin-transform-react-jsx
		isProd
			? react({
					babel: {
						plugins: ["@babel/plugin-transform-react-jsx"],
					},
			  })
			: [],

		// 根据 tsconfig 检查代码的类型和语法错误
		checker({
			typescript: {
				tsconfigPath: path.resolve(__dirname, "./tsconfig.json"),
			},
		}),

		// 压缩代码文件
		compression({
			compressionOptions: {
				ext: ".gz",
				algorithm: "gzip",
				deleteOriginFile: false,
				verbose: false,
			},
		}),

		// 创建HTML
		createHtmlPlugin({
			inject: {
				data: {
					title: "后台系统",
				},
			},
			template: "./index.html",
		}),

		// 处理svg
		svgr({
			svgrOptions: { icon: true },
		}),

		// 用于 web worker
		comlink(),
	],

	// 定义 Web Worker 插件,使用 Comlink 插件
	worker: {
		plugins: [comlink()],
	},

	// 优化依赖配置项
	optimizeDeps: {
		// esbuild 配置
		esbuildOptions: {
			// 指定对 .js 文件使用 jsx 加载器进行编译
			loader: { ".js": "jsx" },
			plugins: [
				{
					name: "load-js-files-as-jsx",
					setup(build) {
						build.onLoad({ filter: /src\/.*\.js$/ }, (args) => ({
							loader: "jsx",
							contents: fs.readFileSync(args.path, "utf8"),
						}));
					},
				},
			],
		},
	},

	// 配置 CSS 处理行为
	css: {
		// CSS 模块化支持
		modules: {
			localsConvention: "camelCaseOnly",
		},
		// 预处理器配置
		preprocessorOptions: {
			scss: {
				javascriptEnabled: true,
			},
			less: {
				javascriptEnabled: true,
				modifyVars: {
					prefixCls: "inspection",
					"root-entry-name": "default",
				},
				plugins: [new LessPluginImportNodeModules()],
			},
		},
		// PostCSS 配置
		postcss: {
			plugins: [
				autoprefixer({
					overrideBrowserslist: ["Chrome > 50", "ff > 31", "ie 11"],
				}),
			],
		},
	},

	// 输出目录&构建选项配置
	build: {
		outDir: "dist/system",
		chunkSizeWarningLimit: 1024,
		minify: "esbuild",
		// 配置 Rollup 的构建参数
		rollupOptions: {
			output: {
				chunkFileNames: "assets/js/[name]-[hash].js",
				entryFileNames: "assets/js/[name]-[hash].js",
				assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
			},
		},
	},

	// 配置模块别名
	resolve: {
		alias: [
			{ find: /^~/, replacement: "" },
			{ find: "@", replacement: path.resolve(__dirname, "./src") },
			{ find: "icons", replacement: path.resolve(__dirname, "./src/components/Icons") },
			{ find: "App", replacement: path.resolve(__dirname, "./src/app") },
			{ find: "common", replacement: path.resolve(__dirname, "./src/common") },
		],
	},

	// 配置开发服务器
	server: {
		// 允许跨域
		cors: true,
		// 允许来自任何域名的跨域请求,设置CORS响应头。
		headers: {
			"Access-Control-Allow-Origin": "*",
		},
		// 设置本地开发服务器的端口号
		port: DEV_PORT,
		// 启用热模块替换,设置开发服务器的主机名和端口号。
		hmr: {
			host: DEV_HOST,
			port: DEV_PORT,
		},
		//  使用HTTPS协议,提供安全的通信机制。配置SSL证书,读取SSL证书文件的路径。
		https: {
			key: fs.readFileSync("./public/.cert/key.pem"),
			cert: fs.readFileSync("./public/.cert/rootCA.pem"),
		},
		// 代理服务器
		proxy,
	},
});

配置项:

  • base 指定基础路径。
  • plugins Vite 插件数组,包含 React、Qiankun、TypeScript 校验、Gzip 压缩、HTML 模板、SVG 图标转换和 Comlink。
  • worker 定义 Web Worker 插件,使用了 Comlink 插件。
  • optimizeDeps 配置优化依赖项的选项,使用了 esbuild。
  • css 配置 CSS 预处理器和 PostCSS 插件。使用了 SCSS 和 Less 预处理器以及 Autoprefixer 插件。
  • build 指定输出目录和构建选项。其中包括输出目录、代码压缩、Rollup 配置等。
  • resolve 配置模块别名,用于在代码中使用简洁的模块路径。
  • assetsInclude 配置需要包含的静态资源。
  • server 配置开发服务器的选项,包括端口号、跨域、热更新、代理等。

优化插件:

  • vite-plugin-compression:此插件可以对构建出来的文件进行压缩,从而减小文件大小,提高页面加载速度。
  • vite-plugin-style-import:此插件可以让你在项目中使用 CSS 类库,比如 Ant Design 或者 Element Plus 等,从而避免了在项目中手动引入这些库的麻烦。
  • vite-plugin-optimize-css:此插件可以对 CSS 进行优化,比如去除注释、删除空格等,从而减小 CSS 文件大小,提高页面加载速度。
  • vite-plugin-svg-icons:如果项目中需要使用大量的 SVG 图标,可以使用此插件进行优化,将 SVG 图标转换成雪碧图,从而减少 HTTP 请求次数。
  • vite-plugin-stylelint:此插件可以在构建项目时对 CSS 代码进行静态检查,避免代码中出现错误和不规范的写法。
  • vite-plugin-externals:此插件可以将一些常用的第三方库从打包过程中排除,从而减少打包后文件的体积。
  • vite-plugin-eslint:此插件可以在构建项目时对 JavaScript 代码进行静态检查,避免代码中出现错误和不规范的写法。
  • vite-plugin-imagemin:此插件可以对图片进行压缩,从而减小图片文件大小,提高页面加载速度。
@bouquetrender bouquetrender changed the title Vite 项目配置指南 Vite 构建工具配置指南 Apr 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant