【问题标题】:How to make an import shortcut/alias in create-react-app?如何在 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 配置的尝试都可能会破坏一些设置,或者您将不得不进行密集配置。你真的需要这个改变吗?如果您需要更短的导入,如何使用相对路径?
  • @EmileBergeron 这个问题是关于 aliases 而不是相对/绝对路径
  • @DennisVash 别名是另一个线程中列出的解决方案之一,这个问题是重复的。
  • 在您的副本中,只有一次提及别名,其相关答案是答案库的出版物。

标签: javascript reactjs webpack alias create-react-app


【解决方案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 显示的方式相同,但形式简单)

    1. 安装 - 安装和设置 CRACO。
    yarn add @craco/craco
    
    # OR
    
    npm install @craco/craco --save
    
    1. 在根目录下创建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'),
        }
      },
    };
    
    1. 在您的 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 文件中。

      【讨论】:

        猜你喜欢
        • 2018-10-12
        • 2020-03-24
        • 1970-01-01
        • 2020-09-18
        • 1970-01-01
        • 1970-01-01
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多