如何在Vite React JS项目中设置和使用别名?

问题描述 投票:0回答:1

我正在开发一个使用 Vite 作为捆绑器的 React JS 项目,我想使用别名改进我的项目的模块导入路径。有人可以提供有关如何在 Vite 项目中设置和使用别名的分步指南吗?

我已经将以下配置添加到我的package.json和vite.config.js中:

package.json

{
  "name": "mern-wp-lms",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite --host",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 5",
    "preview": "vite preview"
  },
  "dependencies": {
    // existing dependencies
  },
  "devDependencies": {
    // existing devDependencies
  },
  "vite": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["src/components/*"]
    }
  }
}

vite.config.js:


import path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

const __filename = import.meta.url;
const __dirname = path.dirname(__filename);

export default defineConfig({
  plugins: [react()],
  optimizeDeps: {
    exclude: ["js-big-decimal"],
  },
  server: {
    port: 8000,
  },
  resolve: {
    alias: { "components": path.resolve(__dirname, "./src/components") },
  },
});

但是,当我尝试在代码中使用别名导入组件时,它似乎没有按预期工作。例如:

`import Header from "components/Header";`

我缺少什么,如何在我的 Vite React 项目中正确设置和使用别名?已经尝试了网络上所有可能的方法和选项。如:

如何在vite React中设置多个别名?

https://www.linkedin.com/pulse/setting-up-aliases-vite-react-typescript-aurelian-spodarec-/

https://dev.to/avxkim/setup-path-aliases-w-react-vite-ts-poa

如何在vite React中设置多个别名?

提前感谢您的帮助!

javascript reactjs vite alias mern
1个回答
0
投票

需要在 package.jsonvite.config.js 中进行一些调整,才能在 Vite React 项目中正确设置和使用别名。

package.json

  "baseUrl": "./src",
  "paths": {
    "@assets/*": [
      "assets/* "
    ],
    "@components/*": [
      "components/*"
    ],
    "@features/*": [
      "features/*"
    ],
    "@pages/*": [
      "pages/*"
    ],
    "@theme/*": [
      "@theme/*"
    ],
    "@utils/*": [
      "@utils/*"
    ]
  }
```

**vite.config.js**

```
 resolve: {
    alias: {
      assets:"/src/assets",
      components: "/src/components",
      mockData:"/src/data",
      features:"/src/features",
      pages: "/src/pages",
      theme: "/src/theme",
      utils: "/src/utils",
    },
  },
```

And import as `import Header from "components/Header";`


© www.soinside.com 2019 - 2024. All rights reserved.