如何添加导入快捷方式-别名 [英] How to add import shortcuts - alias
问题描述
我创建了一个全新的React应用
I've created a brand new react app
create-react-app demo
我需要为某些目录/组件创建别名:
I need to create alias for some directories/components like:
import { Header } from '@uicomponents'
@uicomponents
是路径' src/hello/this/is/the/path/to/ui/components
'
所有在线教程都告诉我可以使用 resolve.alias
使用别名导入,但是我想知道如何使用全新的react应用来做到这一点?
All online tutorials telling that I can use alias imports using resolve.alias
, but I'm wondering how to do this with brand-new react app?
没有.babelrc或webpack.config.js文件.
Theres is no .babelrc or webpack.config.js files.
请帮忙吗?
推荐答案
如果尚未从CRA中退出应用程序,则可以在中使用
文件. NODE_PATH
来为源目录添加别名..env NODE_PATH =/src/hello/this/is/the/path/to/ui/components
.
If you haven't ejected your application from CRA, then you can alias your source directory with using NODE_PATH
in your .env
file. NODE_PATH=/src/hello/this/is/the/path/to/ui/components
.
如果别名没有弹出,则不允许您执行@uicomponents或具有多个别名.这是GitHub上的问题,讨论了该问题以及相关的 CRA页面有关环境变量.
If you alias without ejecting, it won't allow you to do the @uicomponents or have multiple aliases. Here's an issue on GitHub that talks about it and the relevant CRA page on environment variables.
如果已弹出,则可以在Webpack配置文件中设置别名,并可以根据需要进行导入:
If you have ejected you can set the alias in the Webpack configuration files and be able to import like you want:
...
resolve: {
alias: {
'@uicomponents': '/src/hello/this/is/the/path/to/ui/components'
}
},
...
这篇关于如何添加导入快捷方式-别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!