如何在 create-react-app 中创建导入快捷方式/别名?

     2023-02-19     18

关键词:

【中文标题】如何在 create-react-app 中创建导入快捷方式/别名?【英文标题】:How to make an import shortcut/alias in create-react-app? 【发布时间】:2020-11-13 23:08:58 【问题描述】:

如何在 create-react-app 中设置导入快捷方式/别名? 从此:

import  Layout  from '../../Components/Layout'

到这里:

import  Layout  from '@Components/Layout'

我有一个webpack 4.42.0 版本。 我的根目录中没有 webpack.config.js 文件。我尝试在里面创建一个自己的代码:

const path = require('path')

module.exports = 
  resolve: 
    alias: 
      '@': path.resolve(__dirname, 'src/'),
    
  
;

但它似乎不起作用。我在.env 文件中看到了NODE_PATH=. 变体。但我相信,它已被弃用 - 最好不要使用。而且,我有一个posstcss.config.js 文件。因为我已经安装了 TailwindCss 并在那里导入了 CSS 库。我尝试在那里粘贴相同的代码,但它也没有工作。

【问题讨论】:

使用create-react-app 时,使用react-script 读取webpack 配置,它真正处理使用CRA 时的所有进程。任何运行并行 webpack 配置的尝试都可能会破坏一些设置,或者您将不得不进行密集配置。你真的需要这个改变吗?如果您需要更短的导入,如何使用相对路径? 这能回答你的问题吗? How to avoid using relative path imports (/../../../redux/action/action1) in create-react-app @EmileBergeron 这个问题是关于 aliases 而不是相对/绝对路径 @DennisVash 别名是另一个线程中列出的解决方案之一,这个问题是重复的。 在您的副本中,只有一次提及别名,其相关答案是答案库的出版物。 【参考方案1】:

混淆术语的注意事项

// Absolute path: paths which are relative to a specific path
import Input from 'components' // src/components
import UsersUtils from 'page/users/utils' // src/page/users/utils

// Alias path: other naming to specific path
import Input from '@components' // src/components
import UsersUtils from '@userUtils' // src/page/users/utils

为了让 webpack 的 aliases 工作,你需要配置默认的 webpack.config.jscreate-react-app

官方方式是to use the eject script。

推荐的方式是使用库而不弹出,比如craco

在关注installation 之后,将craco.config.js 添加到具有所需配置的根文件夹中。

我的例子:

// craco.config.js
const path = require(`path`);
const alias = require(`./src/config/aliases`);

const SRC = `./src`;
const aliases = alias(SRC);

const resolvedAliases = Object.fromEntries(
  Object.entries(aliases).map(([key, value]) => [key, path.resolve(__dirname, value)]),
);

module.exports = 
  webpack: 
    alias: resolvedAliases,
  ,
;

aliases.js (./src/config/aliases) 导出辅助函数的位置:

const aliases = (prefix = `src`) => (
  '@atoms': `$prefix/components/atoms`,
  '@molecules': `$prefix/components/molecules`,
  '@organisms': `$prefix/components/organisms`,
  '@templates': `$prefix/components/templates`,
  '@components': `$prefix/components`,
  '@config': `$prefix/config`,
  '@enums': `$prefix/enums`,
  '@hooks': `$prefix/hooks`,
  '@icons': `$prefix/components/atoms/Icons`,
  '@styles': `$prefix/styles`,
  '@utils': `$prefix/utils`,
  '@state': `$prefix/state`,
  '@types': `$prefix/types`,
  '@storybookHelpers': `../.storybook/helpers`,
);

module.exports = aliases;

VSCode 智能感知

另外,你应该在VSCode中为路径IntelliSense添加jsconfig.json文件(或tsconfig.json),see followup question。

现在这样的带有 IntelliSense 的代码可以工作了:

// NOTE THAT THOSE ARE ALIASES, NOT ABSOLUTE PATHS
// AutoComplete and redirection works
import ColorBox from '@atoms';
import RECOIL_STATE from '@state';

【讨论】:

【参考方案2】:

按照以下步骤进行归档的最简单方法。 (与@DennisVash 显示的方式相同,但形式简单)

    安装 - 安装和设置 CRACO。
yarn add @craco/craco

# OR

npm install @craco/craco --save
    在根目录下创建craco.config.js文件并配置CRACO:
/* craco.config.js */
const path = require(`path`);

module.exports = 
  webpack: 
    alias: 
      '@': path.resolve(__dirname, 'src/'),
      '@Components': path.resolve(__dirname, 'src/components'),
      '@So_on': path.resolve(__dirname, 'src/so_on'),
    
  ,
;
    在您的 package.json 文件的脚本部分更新对 react-scripts 的现有调用以使用 craco CLI:
/* package.json */

"scripts": 
   "start": "craco start",
   "build": "craco build",
   "test": "craco test"

完成!设置完成。

现在让我们测试一下。

// Before
import Button from "./form/Button" 
import  Layout  from '../../Components/Layout'

// After
import Button from "@/form/Button"
import  Layout  from '@Components/Layout'

文档Craco

谢谢。 :)

【讨论】:

【参考方案3】:

Create React App v.3 终于可以实现了

简单地说:


  "compilerOptions": 
    "baseUrl": "src"
  ,
  "include": ["src"]

如果您使用 Typescript,请输入 jsconfig.jsontsconfig.json

article 非常棒。

【讨论】:

你总是可以通过jsconfig.json进行绝对导入,问题是关于制作aliases @DennisVash 关于导入别名的问题不是,而是关于导入路径快捷方式,这个答案正确地解决了这个问题。别名是减少导入路径长度的多种方法之一这一事实并没有使这个答案无效。【参考方案4】:

如果你想使用:

// this:
import MyUtilFn from 'utils/MyUtilFn';
// Instead of this:
import MyUtilFn from '../../../../utils/MyUtilFn';

使用节点模块插件来解析网址https://www.npmjs.com/package/babel-plugin-module-resolver。通过安装它并将其添加到您的 webpack/babel.rc 文件中。

【讨论】:

如何在使用 create-react-app 时更改 npm 版本

】如何在使用create-react-app时更改npm版本【英文标题】:HowcanIchangenpmversionwhileusingcreate-react-app【发布时间】:2019-05-2618:23:42【问题描述】:我正在尝试在命令行中运行create-react-app,但我不断收到以下消息:“您使用的是npm2.15.12... 查看详情

如何在 create-react-app 中指定全局类型声明?

】如何在create-react-app中指定全局类型声明?【英文标题】:Howtospecifyglobaltypedeclarationsincreate-react-app?【发布时间】:2021-08-2319:16:00【问题描述】:我在我的create-react-app项目中设置全局类型时遇到问题。这是我的tsconfig.json文件。"... 查看详情

create-react-app — 如何将 EXTEND_ESLINT 设置为 true?

】create-react-app—如何将EXTEND_ESLINT设置为true?【英文标题】:create-react-app—howtosetEXTEND_ESLINTtotrue?【发布时间】:2020-06-0301:31:15【问题描述】:我在我的项目根目录中创建了一个.env文件,但我是使用环境/变量的新手,所以我不... 查看详情

如何在 create-react-app 上调试 jest 单元测试?

】如何在create-react-app上调试jest单元测试?【英文标题】:howtodebugjestunittestsoncreate-react-app?【发布时间】:2017-02-0910:38:52【问题描述】:我使用create-react-app并且想调试我的单元测试作为Jestdocumentationsays,可以使用以下命令进行调... 查看详情

create-react-app:如何在 React 渲染之前加载 html

】create-react-app:如何在React渲染之前加载html【英文标题】:create-react-app:howtoloadhtmlbeforeReactrenders【发布时间】:2019-08-1004:02:01【问题描述】:我正在尝试在React加载之前添加启动画面。因为我使用的是reactscripts/react-app,所以我... 查看详情

如何在 Windows 7 中使用 create-react-app

】如何在Windows7中使用create-react-app【英文标题】:Howtousecreate-react-appwithWindows7【发布时间】:2022-01-1915:34:53【问题描述】:昨天尝试使用create-react-app启动一个新的react应用。不幸的是,当我使用命令npxcreate-react-appmy-app时,它显... 查看详情

如何在 create-react-app 上使用“/”阻止路由

】如何在create-react-app上使用“/”阻止路由【英文标题】:Howtoblockrouteswith\'/\'oncreate-react-app【发布时间】:2019-11-0904:55:39【问题描述】:我正在创建一个包含四个页面的简单SPA,但我发现了一个导致我的应用程序崩溃的大问题。... 查看详情

如何在 create-react-app 中激活 CORS?

】如何在create-react-app中激活CORS?【英文标题】:HowcanIactivateCORSincreate-react-app?【发布时间】:2019-06-1709:35:46【问题描述】:我已经使用create-react-appcli创建了一个React应用程序。现在我使用外部库做一些请求。(我将库传递给我... 查看详情

如何在生产中基于 create-react-app 的项目中指定端口号?

】如何在生产中基于create-react-app的项目中指定端口号?【英文标题】:Howtospecifyaportnumberinacreate-react-appbasedprojectinproduction?【发布时间】:2018-01-2613:08:08【问题描述】:我正在部署一个网站,其中包含一些使用create-react-app构建的... 查看详情

如何在 create-react-app 中自定义 blueprintjs 外观

】如何在create-react-app中自定义blueprintjs外观【英文标题】:howtocustomizeblueprintjsappearanceincreate-react-app【发布时间】:2018-02-2207:18:59【问题描述】:我是新手,我使用以下代码构建我的应用程序:create-react-appapplicationame--scripts-versio... 查看详情

你如何在带有 Typescript 的 create-react-app 中使用 Mocha?

】你如何在带有Typescript的create-react-app中使用Mocha?【英文标题】:HowdoyouuseMochaincreate-react-appwithTypescript?【发布时间】:2018-11-0800:49:12【问题描述】:我正在使用create-react-app(typescript)来创建React应用程序,但我想使用mocha+酶而不... 查看详情

create-react-app:如何使用 https 而不是 http?

】create-react-app:如何使用https而不是http?【英文标题】:create-react-app:howtousehttpsinsteadofhttp?【发布时间】:2017-11-1808:30:43【问题描述】:我想知道是否有人知道如何在dev上使用https来创建“create-react-app”环境。我在自述文件或快... 查看详情

如何在使用 create-react-app 创建的应用程序中使用带有访问令牌的 API

】如何在使用create-react-app创建的应用程序中使用带有访问令牌的API【英文标题】:HowdoIuseAPIswithaccesstokensinappscreatedwithcreate-react-app【发布时间】:2019-08-0804:36:59【问题描述】:如何在使用create-react-app创建的应用的生产版本中隐... 查看详情

如何使用 create-react-app 在 Jest 测试中忽略生成的 Relay 查询文件?

】如何使用create-react-app在Jest测试中忽略生成的Relay查询文件?【英文标题】:HowtoignoregeneratedRelayqueryfilesinJesttestsusingcreate-react-app?【发布时间】:2020-02-0201:15:04【问题描述】:我使用create-react-app创建了一个React应用并添加了Relay... 查看详情

如何在 create-react-app 中注入没有 REACT_APP 前缀的 dotenv 变量?

】如何在create-react-app中注入没有REACT_APP前缀的dotenv变量?【英文标题】:HowtoinjectdotenvvariableswithoutREACT_APPprefixincreate-react-app?【发布时间】:2020-08-0705:46:33【问题描述】:我有一个项目要从旧版React应用迁移到标准create-react-app一... 查看详情

如何在开发模式而不是生产模式下部署 create-react-app 网站

】如何在开发模式而不是生产模式下部署create-react-app网站【英文标题】:HowcanIdeployacreate-react-appwebsiteindevelopmentmodeinsteadofproduction【发布时间】:2021-02-0423:58:08【问题描述】:我正在为我和我的团队创建的chrome开发工具制作登录... 查看详情

使用 create-react-app 和 Typescript 时如何在构建时加载 .md 文件?

】使用create-react-app和Typescript时如何在构建时加载.md文件?【英文标题】:Howtoloadan.mdfileonbuildwhenusingcreate-react-appandTypescript?【发布时间】:2021-03-3108:32:25【问题描述】:我正在尝试加载要在构建时加载的降价文件。我已经设置了... 查看详情

在开发模式下使用 create-react-app 时如何将应用程序放在子文件夹中?

】在开发模式下使用create-react-app时如何将应用程序放在子文件夹中?【英文标题】:Howtoputtheappinasubfolderwhenusingcreate-react-appinDevelopmentmode?【发布时间】:2019-12-0112:48:36【问题描述】:这里有很多答案,其他地方的博文(包括官... 查看详情