问题描述
我在使用 create-react-app 和 ,已经在谷歌上搜索过但无法解决问题.
I have a problem on set webpack alias path using create-react-app and craco, already googling it but can't solve the problem.
我收到一个错误 Module not found: Can't resolve '@app/App' in 'C:\ReactSandbox\my-project\src
每次我使用命令 yarn 运行应用程序开始
I got an error Module not found: Can't resolve '@app/App' in 'C:\ReactSandbox\my-project\src
everytime i run application using command yarn start
create-react-app my-project
cd my-project
纱线添加@craco/craco
cat >craco.config.js
(见下面的配置)- 在 package.json 的脚本"部分将
react-scripts
替换为craco
(craco start、craco build 等)立> - 编辑文件
src/index.js
(替换第 4 行,见下面的代码) 纱线开始
create-react-app my-project
cd my-project
yarn add @craco/craco
cat > craco.config.js
(see configuration below)- replace
react-scripts
tocraco
on 'script' section on package.json (craco start, craco build, etc) - edit file
src/index.js
(replace line 4, see code below) yarn start
craco.config.js
const path = require("path");
module.exports = {
webpack: {
resolve: {
alias: {
"@app": path.resolve(__dirname, "src/"),
}
}
}
};
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from '@app/App'; //replace './App' into '@app/App'
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
当前结果
Module not found: Can't resolve '@app/App' in 'C:\ReactSandbox\my-project\src
我避免调用相对路径地狱,而不是像../../../../FilterComment.js
这样的导入模块,写@会很干净app/FilterComment.js
I'm avoiding call relative path hell, instead of import module like ../../../../FilterComment.js
, it would be clean to write @app/FilterComment.js
推荐答案
首先 - 告诉 IDE 关于 tsconfig.json 中的别名:
创建单独的文件 tsconfig.paths.json
并添加别名:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@utils/*": ["utils/*"]
}
}
}
将创建的 tsconfig.paths.json
添加到主 tsconfig.json
Add created tsconfig.paths.json
to main tsconfig.json
{
"extends": "./tsconfig.paths.json",
... other staff ...
}
第二 - 告诉 webpack 别名:
为 config-overrides.js
const {
override,
addWebpackAlias
} = require('customize-cra');
const path = require("path");
module.exports = override(
addWebpackAlias({
"@utils": path.resolve(__dirname, "./src/utils"),
}),
);
这篇关于如何在 CRA (create-react-app) 和 craco 中通过 webpack 设置别名路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!