首页 > 解决方案 > 如何在反应中将我的导入缩短为“@dir/subdir/file”中的 import xxx

问题描述

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'

标签: javascriptreactjs

解决方案


确保您的 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/


推荐阅读