簡體   English   中英

絕對導入在 React Vite js 中不起作用

[英]Absolute import is not working in React Vite js

vite 配置無法從 src 文件夾導入消息: Failed to resolve import "redux/1space/letter/inboxSlice" from "src/pages/letter/index.jsx". Does the file exist? / Failed to resolve import "redux/1space/letter/inboxSlice" from "src/pages/letter/index.jsx". Does the file exist? /

import { loadInboxs } from "redux/1space/letter/inboxSlice";

我的vite配置:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import jsconfigPaths from 'vite-jsconfig-paths';
import svgrPlugin from 'vite-plugin-svgr';
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), jsconfigPaths(), svgrPlugin()],
  build: {
    outDir: 'build',
  },
  server: {
    open: true,
    port: 3000
  },
  resolve: {
    alias: {
      '~': path.resolve(__dirname, 'src'),
    },
  },
  esbuild: {
    loader: "jsx",
    include: /.\/src\/.*\.js?$/,
    exclude: [],
    jsx: "automatic",
  },
  optimizeDeps: {
    esbuildOptions: {
      loader: {
        '.js': 'jsx',
      },
    },
  }, 
})

js配置

{
    "compilerOptions": {
        "baseUrl": "src",
        "target": "ESNext",
        "lib": ["dom", "dom.iterable", "esnext"],
        "types": ["vite/client", "vite-plugin-svgr/client"],
    },
    "include": ["src","src/.js"]
  }

你可以通過在你的 vite 配置中添加這些規則來實現這一點:

export default defineConfig({
...
  resolve: {
    alias: [
      { find: '@assets', replacement: '/src/assets' },
      { find: '@components', replacement: '/src/components' },
      { find: '@pages', replacement: '/src/pages' },
    ],
  },
...
});

然后,當您要導入文件時,只需使用您指定的別名即可。

import Navbar from '@components/navbar/Navbar';
import Home from '@pages/home/Home';
import Menu from '@pages/menu/Menu';

不需要js配置文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM