[英]Where's the connection between index.html and index.js in a Create-React-App application?
[英]Why create-react-app alias is not able to find index.js from folder?
在為我的應用程序創建別名時,我遇到了一個奇怪的問題。 我正在嘗試創建別名添加jsconfig.json
看起來像
{
"compilerOptions": {
"lib": [
"dom",
"es2015",
"es2016",
"es6",
"es2017"
],
"target": "es2017",
"module": "es6",
"allowSyntheticDefaultImports": true,
"baseUrl": "./",
"paths": {
"actions/*": ["src/actions/*"],
"public/*": ["public/*"],
"components/*": ["src/components/*"],
"containers/*": ["src/containers/*"],
"constants/*": ["src/constants/*"],
"config/*": ["config/*"],
"helpers/*": ["src/helpers/*"],
"stores/*": ["src/stores/*"],
"styles/*": ["src/styles/*"]
}
},
"exclude": ["node_modules", "**/node_modules/*"]
}
在這種情況下,它無法找到任何組件別名。
我將 json 文件更改為
{
"compilerOptions": {
"lib": [
"dom",
"es2015",
"es2016",
"es6",
"es2017"
],
"target": "es2017",
"module": "es6",
"allowSyntheticDefaultImports": true,
"baseUrl": "./src/",
"paths": {
"actions/*": ["actions/*"],
"public/*": ["public/*"],
"components/*": ["components/*"],
"containers/*": ["containers/*"],
"constants/*": ["constants/*"],
"config/*": ["config/*"],
"helpers/*": ["helpers/*"],
"stores/*": ["stores/*"],
"styles/*": ["styles/*"]
}
},
"exclude": ["node_modules", "**/node_modules/*"]
}
它能夠獲取組件別名但拋出錯誤Cannot find file: 'index.js' does not match the corresponding name on disk: './src/components/Checkbox/CheckBox'.
當我嘗試將其作為import Checkbox from 'components/Checkbox';
. 我的文件夾結構看起來像
mainDir/
config/
public/
src/
component/
Checkbox/
index.js
jsconfig.json
package.json
我該如何解決這個問題? 有沒有其他方法可以使用create-react-app
創建別名?
在create-react-app
項目中, src
文件夾之外的源文件不會被轉譯。 [1]
由於這個原因,直接從src
文件夾之外使用JSX 語法的 es6 模塊導入會失敗。
通常的做法是在src
文件夾中為其外部的模塊創建符號鏈接,並設置別名以從src
文件夾解析。 例如
"baseUrl": "src",
"paths": {
"actions": ["actions/*"],
"public": ["public/*"],
"components": ["components/*"],
"containers": ["containers/*"],
"constants": ["constants/*"],
"config": ["config/*"],
"helpers": ["helpers/*"],
"stores": ["stores/*"],
"styles": ["styles/*"]
}
符號鏈接外部模塊
ln -s ../config/ ./src/
ln -s ../public/ ./src/
使用別名解決方案解決您的問題。 它可以從jsconfig.json或tsconfig.json加載您的路徑。
對於您使用jsconfig.json
的情況,配置非常簡單,如下所示:
// config-overrides.js:
const {alias, configPaths} = require('react-app-rewire-alias')
module.exports = function override(config) {
alias(configPaths())(config)
return config
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.