如何在 CRA (create-react-app) 和 craco 中通过 webpack 设置别名路径?

IT技术 javascript reactjs webpack
2021-05-21 19:26:06

我在使用create-react-appcraco设置webpack别名路径时遇到问题,已经使用谷歌搜索但无法解决问题。

Module not found: Can't resolve '@app/App' in 'C:\ReactSandbox\my-project\src每次我使用命令运行应用程序时都会出错yarn start

重现步骤:

  1. create-react-app my-project
  2. cd my-project
  3. yarn add @craco/craco
  4. cat > craco.config.js (见下面的配置)
  5. 替换react-scriptscracopackage.json 上的“脚本”部分(craco start、craco build 等)
  6. 编辑文件src/index.js (替换第 4 行,见下面的代码)
  7. yarn start

craco.config.js

const path = require("path");

module.exports = {
  webpack: {
    resolve: { 
      alias: {
        "@app": path.resolve(__dirname, "src/"),
      }
    }    
  }
};

源代码/索引.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

预期的

我避免调用相对路径地狱,而不是像这样的导入module../../../../FilterComment.js,写起来很干净@app/FilterComment.js

4个回答

首先 - 告诉 IDE 关于 tsconfig.json 中的别名:

创建单独的文件tsconfig.paths.json并添加别名:

{
   "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
         "@utils/*": ["utils/*"]
      }
   }
}

添加创建tsconfig.paths.json到主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"),
   }),
);

解决carco:

你需要安装craco-alias,然后写在 craco.config.js

    const CracoAlias = require('craco-alias')

    module.exports = {
      plugins: [
        {
          plugin: CracoAlias,
          options: {
            source: 'tsconfig',
            baseUrl: '.',
            tsConfigPath: './tsconfig.path.json',
          },
        },
      ],
    }

tsconfig.path.json

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/*": ["src/*"],
          "@svg/*": ["src/assets/svg/*"],
          "@img/*": ["src/assets/images/*"],
          "@icons/*": ["src/assets/icons/*"],
          "@shared/*": ["src/shared/*"],
          "@components/*": ["src/components/*"],
          "@hooks/*": ["src/hooks/*"],
          "@constants/*": ["src/constants/*"],
          "@layout/*": ["src/layout/*"],
          "@services/*": ["src/services/*"]
        }
      }
    }

配置文件

    {
      "extends": "./tsconfig.path.json",
      "compilerOptions": {
        "target": "es5",
        "lib": [
          "dom",
          "dom.iterable",
          "esnext"
        ],
        "allowJs": true,
        "checkJs": false,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "declaration": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react-jsx",
        "noFallthroughCasesInSwitch": true,
        "removeComments": true
      },
      "include": [
        "src",
        "src/configs",
        "react-app-env.d.ts"
      ]
    }

我的 craco.config.js 如下所示,它有效:

const path = require('path');

module.exports = {
    // ...
    webpack: {
        alias: {
            '@': path.join(path.resolve(__dirname, './src')),
        }
    }
}

就这样保留你的文件craco.config.js,你需要再添加1个名为jsconfig.json

它的内容:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2016",
    "jsx": "preserve",
    "checkJs": true,
    "baseUrl": "./src/",
    "paths": {
      "@app/*": ["./*"]
    }
  },
  "exclude": ["node_modules", "**/node_modules/*"]
}

然后你可以从绝对路径导入 @app/FilterComment.js

它也适用于 VSCode(编辑器现在知道@app指向哪里)。但是,如果您希望 VSCode 自动执行导入,那么您应该为其添加更多配置以强制它始终从绝对路径进行导入。

文件.vscode/settings.json 内容:

{
  "javascript.preferences.importModuleSpecifier": "non-relative"
}