简体   繁体   中英

How to set multiple aliases in vite react?

Vite by default does not support src alias like

import counterReducer from "@src/pages/counter/counter.slice";

Every time you will have to pass the full relative path like this

import counterReducer from "../../src/pages/counter/counter.slice";

Is there any way we can shorten these relative paths?

Yes, vite doesn't come with the default configuration of aliases, but you can define your own aliases.

Step: 1 Open "vite.config.js" and add your aliases. vite.config.js

 import { defineConfig } from "vite"; import react from "@vitejs/plugin-react-swc"; import path from "path"; // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], resolve: { alias: { "@": path.resolve(__dirname, "./src/"), components: `${path.resolve(__dirname, "./src/components/")}`, public: `${path.resolve(__dirname, "./public/")}`, pages: path.resolve(__dirname, "./src/pages"), types: `${path.resolve(__dirname, "./src/@types")}`, }, }, });

Step 2: Open tsconfig.json or jsconfig.json and append this code under compiler options. tsconfig.json文件

 "baseUrl": ".", "paths": { "@/*": ["./src/*", "./dist/*", ""], "pages/*": ["src/pages/*"], "components/*": ["src/components/*"], "types/*": ["src/@types/*"], "public/*": ["public/*"] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM