【问题标题】:absolute path with react, react-app-rewire and typescriptreact、react-app-rewire 和 typescript 的绝对路径
【发布时间】:2020-04-20 00:47:33
【问题描述】:

我正在使用create-react-app + typescript,我想添加绝对路径。

我试图达到我可以使用绝对路径的目的,如下所示:

而不是import x from '../../../components/shell/shell'

使用import x from '@components/shell/shell'

这里是 tsconfig.json 文件:

{
  "extends": "./paths.json",
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "baseUrl": "src",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

我使用扩展文件作为路径,因为出于某种原因npm start 会覆盖该文件。 paths.json 文件也是如此:

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

我还有一个 .env 文件:

NODE_PATH=src

我安装了react-app-rewire,所以我可以配置路径, 我的 config-ovverrides.js 文件看起来像这样:

module.exports = {
  paths: function(paths, env) {
    // ...add your paths config
    return paths;
  }
};

我坚持连接所有点,它不起作用,我仍然看不到我需要做什么才能配置 webpack 路径对象;

如何在 cra、ts 和 rewire 中实现路径?

【问题讨论】:

    标签: reactjs webpack


    【解决方案1】:

    您需要使用@ 语法吗?

    你能使用以下语法吗:

    import x from 'components/shell/shell'
    

    ?

    如果是这样,请参阅CRA Absolute Imports 的文档。

    对于 Typescript,您的 tsconfig.json 变为:

    {
      "compilerOptions": {
        // ... usual options ...
        "baseUrl": "src",
      },
      // ... include, etc...
    }
    

    开箱即用,这将允许您导入 src 作为基本目录。

    所以你的语法变成了:

    import x from 'components/shell/shell';
    

    这将是摩擦最小的选择...

    不过……

    如果您绝对需要 @ 语法,那么要让 rewire 正常工作,需要更多的 jiggery-pokery。我发现重新连接以使用该语法的唯一方法是包含 webpack 别名重写。

    所以流程是(请根据您的应用程序需要更新路径):

    1. 在您的tsconfig.json 旁边创建一个tsconfig.paths.json,其中包含:
    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@components": ["src/components/*"],
        }
      }
    }
    
    1. extend 更新您的tsconfig.json
    {
      "compilerOptions": {
        // ... standard options ...
      },
      "include": [
        "src"
      ],
      "extends": "./tsconfig.paths.json"
    }
    

    运行构建命令(npm run build)时,脚本会抛出以下错误:

    The following changes are being made to your tsconfig.json file:
      - compilerOptions.paths must not be set (aliased imports are not supported)
    

    extend 选项可以缓解这种情况。

    1. config-overrides.js添加一个webpack别名:
    const path = require('path');
    const { override, addWebpackAlias } = require('customize-cra');
    
    module.exports = override(
      addWebpackAlias({
        '@components': path.resolve(__dirname, 'src/components'),
      })
    );
    

    这个例子使用了包customize-cra,它有一堆有用的解析器来覆盖。 (如果您不想使用它,则需要在传递给override 函数的config 对象上设置config.resolve.alias 属性)

    现在假设您已将所有脚本更新为使用react-app-rewired,您应该可以使用以下语法:

    import x from '@components/shell/shell';
    

    【讨论】:

    • 您好,谢谢您的回答。我不一定要使用“@”。
    【解决方案2】:

    您可以使用 5 个简单的步骤无需弹出来解决它:

    第 1 步:将 react-app-rewired 添加到您的 devDependencies

    yarn add -D react-app-rewirednpm intall react-app-rewired --save-dev

    第 2 步:安装后,您可以将 package.json 默认 ReactsJS 脚本更改为:

    "scripts": {  
      "start": "react-app-rewired start",  
      "build": "react-app-rewired build",  
      "test": "react-app-rewired test",  
      "eject": "react-app-rewired eject" 
    }
    

    第 3 步:在根路径上创建一个名为 tsconfig.paths.json 的新文件,其内容如下:

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "services/*": ["./src/shared/services/*"],
          "interfaces/*": ["./src/shared/interfaces/*"]
        }
      }
    }
    

    提示 1:您可以选择要使用的路径,例如: @services, @interface, @src, ~, @, etc 只需更改 "paths": {} 中的键即可

    同样适用于它的值:["src/shared/services/<em>"], ["src/shared/interfaces/</em>"], ["src/*"],这里使用相对路径。

    第四步:进入tsconfig.json,在"compilerOptions"之前你需要扩展你刚刚创建的tsconfig.paths.json

    像这样:

    {
      "extends": "./tsconfig.paths.json",
      ...//rest of file infos compilerOptions, include... whatever
    }
    

    第 5 步:创建一个新文件 config-overrides.js,在其上添加您的别名和相对路径:

    const path = require('path');
    
    module.exports = function override(config) {
      config.resolve = {
        ...config.resolve,
        alias: {
          ...config.alias,
          'services': path.resolve(__dirname, 'src/shared/services'),
          'interfaces': path.resolve(__dirname, 'src/shared/interfaces')
        },
      };
    
      return config;
    };
    

    提示 2:如果您使用的是 <strong>eslint</strong>,请记住有一个 .eslintignore 文件并在其中添加 config-overrides.js

    重启你的 IDE 或文本编辑器,在我的例子中是 VSCode。

    完成了!现在只需运行 yarn startnpm run start

    【讨论】:

      【解决方案3】:

      不再支持路径别名

      但您现在可以这样做,直接导入相对于src 目录的文件

      转到您的tsconfig.json 文件添加baseUrl"."

      "compilerOptions": {
          "baseUrl":".",
          ...
      

      然后你可以直接从src目录导入东西

      import Myfile from "src/myfile.js"
      

      这对我有用!

      【讨论】:

        猜你喜欢
        • 2019-02-06
        • 2019-01-21
        • 2019-11-25
        • 2019-06-28
        • 2021-05-25
        • 2020-07-28
        • 2021-06-25
        • 2020-12-25
        • 2020-01-08
        相关资源
        最近更新 更多