簡體   English   中英

如何在反應中將我的導入縮短為“@dir/subdir/file”中的 import xxx

[英]how can i shorten my imports as import xxx from “@dir/subdir/file” in react

我已將根目錄中的jsconfig.json配置為:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@dir/*": ["./src/app/dir/*"]
    }
  },
  "exclude": ["node_modules", "**/node_modules/*"],
}

我的文件夾結構如下所示:

root  
│
└───src
│   |__app
|   |    |__dir 
|   |    |    |__subdir1 
|   |    |    |     |__file1.js and other js files
|   |    |    |__subdir2
|   |    |          |__file2.js
|
|__jsconfig.json
|__package.json
|__...other root files 


我的目標是使用將文件 1 中的某些內容導入文件 2

import xyz from '@dir/subdir1/file1'

而不是使用

import xyz from '../subdir1/file1'

確保您的 webpack 配置webpack.config.js最終具有:

對於彈出 webpack 配置后的 CRA,您應該能夠導航到webpack.config.js並將您的別名添加到列表中。

 resolve {
     alias: {
       "@dir": "src/app/dir"
    },
 }

或在 Next.js next.config.js

 config.resolve.alias = {
   ...config.resolve.alias,
   "@dir": "src/app/dir"
};

查看此文檔: https://webpack.js.org/configuration/resolve/

你可以使用這個 babel 插件: https://github.com/tleunen/babel-plugin-module-resolver

暫無
暫無

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

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