我已经创建了一个全新的反应应用
create-react-app demo
我需要为某些目录/组件创建别名,如:
import { Header } from '@uicomponents'
@uicomponents
是路径“src/hello/this/is/the/path/to/ui/components
”
所有在线教程告诉我可以使用resolve.alias
使用别名导入,但我想知道如何使用全新的反应应用程序进行此操作?
Theres不是.babelrc或webpack.config.js文件。
请帮忙吗?
答案 0 :(得分:6)
如果您尚未从CRA中弹出应用程序,则可以使用NODE_PATH
文件中的.env
为源目录添加别名。 NODE_PATH=/src/hello/this/is/the/path/to/ui/components
。
如果别名没有弹出,则不允许您执行@uicomponents或具有多个别名。这是GitHub上的一个issue,它讨论了它和环境变量的相关CRA page。
如果您已经弹出,可以在Webpack配置文件中设置别名,并且可以按照您想要的方式导入:
...
resolve: {
alias: {
'@uicomponents': '/src/hello/this/is/the/path/to/ui/components'
}
},
...
答案 1 :(得分:3)
使用 alias 解决方案,该解决方案提供别名和多个src
文件夹:
使用react-app-rewired
或customize-cra
:
// config-overrides.js:
const {alias} = require('react-app-rewire-alias')
module.exports = function override(config) {
alias({
'@uicomponents': 'src/hello/this/is/the/path/to/ui/components',
"@lib": "lib", // in root of app outside of src
})(config)
return config
}
与craco
一起使用:
// craco.config.js
const {CracoAliasPlugin, configPaths} = require('react-app-rewire-alias')
module.exports = {
plugins: [
{
plugin: CracoAliasPlugin,
options: {alias: configPaths('./tsconfig.paths.json')}
}
]
}
您可以直接指定别名映射,也可以使用configPaths()
答案 2 :(得分:2)