如何在 CRA (create-react-app) 和 craco 中通过 webpack 设置别名路径? [英] How to set alias path via webpack in CRA (create-react-app) and craco?

查看:130
本文介绍了如何在 CRA (create-react-app) 和 craco 中通过 webpack 设置别名路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 create-react-appcraco,已经在谷歌上搜索过但无法解决问题.

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

  1. create-react-app my-project
  2. cd my-project
  3. 纱线添加@craco/craco
  4. cat >craco.config.js (见下面的配置)
  5. 在 package.json 的脚本"部分将 react-scripts 替换为 craco (craco start、craco build 等)
  6. 编辑文件 src/index.js (替换第 4 行,见下面的代码)
  7. 纱线开始
  1. create-react-app my-project
  2. cd my-project
  3. yarn add @craco/craco
  4. cat > craco.config.js (see configuration below)
  5. replace react-scripts to craco on 'script' section on package.json (craco start, craco build, etc)
  6. edit file src/index.js (replace line 4, see code below)
  7. 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 设置别名路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆