繁体   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