如何添加导入快捷方式 - 别名

时间:2018-05-02 10:37:58

标签: reactjs

我已经创建了一个全新的反应应用

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文件。

请帮忙吗?

3 个答案:

答案 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-rewiredcustomize-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()

jsconfig.json tsconfig.json 加载它

答案 2 :(得分:2)

最近,我创建了一个用于向CRA添加别名的工具。

链接:GitHubnpm

它适用于每个命令(npm startnpm testrun build build),并允许传递任何CLI参数。

您只需要在您的package.json中创建(或编辑)jsconfig.json / tsconfig.json(它也适用于TS)并将react-scripts替换为cra-alias

自述文件中列出了完整的文档。

我希望它能对某人有所帮助:)

相关问题