[英]How to add import shortcuts - alias
我創建了一個全新的 React 應用程序
create-react-app demo
我需要為某些目錄/組件創建別名,例如:
import { Header } from '@uicomponents'
其中@uicomponents
是路徑“ src/hello/this/is/the/path/to/ui/components
”的快捷方式
所有在線教程都告訴我可以使用resolve.alias
使用別名導入,但我想知道如何使用全新的 React 應用程序執行此操作?
沒有 .babelrc 或 webpack.config.js 文件。
請問有什么幫助嗎?
如果您還沒有從 CRA 中彈出您的應用程序,那么您可以在您的.env
文件中使用NODE_PATH
為您的源目錄設置別名。 NODE_PATH=/src/hello/this/is/the/path/to/ui/components
。
如果您在不彈出的情況下使用別名,則不允許您執行 @uicomponents 或具有多個別名。 這是 GitHub 上的一個問題,討論了它以及有關環境變量的相關CRA 頁面。
如果你已經彈出,你可以在 Webpack 配置文件中設置別名,並能夠像你想要的那樣導入:
...
resolve: {
alias: {
'@uicomponents': '/src/hello/this/is/the/path/to/ui/components'
}
},
...
更新:
我建議你使用Craco 。
它允許您自定義webpack
/ babel
/ 在內部react-scripts
中使用的任何其他工具。
Webpack
和Jest
別名也不例外。
最近我專門為這些目的創建了一個名為craco-alias
的插件。
這個插件會自動為你生成 webpack 和 jest 別名。
您只需要安裝Craco ,為其編寫一個小配置,然后創建(或編輯)您的jsconfig.json
/ tsconfig.json
(它也適用於 TS)並在craco-alias
配置對象中指定別名source
。
這很簡單 - 您可以在 README 頁面上找到所有示例。
當然,它適用於每個命令( npm start
、 npm test
、 run build build
)並允許傳遞任何 CLI 參數。
但是,唯一的問題是插件只支持路徑別名,並且不能正確處理模塊別名。
我希望它會幫助某人:)
使用提供別名和多個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()
從jsconfig.json或tsconfig.json加載它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.