使用crate-react-app创建的项目配置alias

使用crate-react-app创建的项目配置alias,这样之后在项目中直接可以使用别名来访问某个文件目录,从而快速引用某个文件,如使用这个命令创建的项目中,我们这 src/ 目录下创建一个 components/ 文件夹,如果想在项目中快速引用 components/Tab/index.tsx 文件的话,我们可这样写: import Tab from '@Component/Tab/index ,那么我们是怎么实现的呢?

 

首先我们在使用 crate-react-app 创建项目后,进入到项目中执行 npm run eject 命令,将 react-script 插件中封装的 webpack、sass等配置文件暴露到项目中(注意此命令不可逆,也就是说,一旦解压后就不能更新 react-script 插件版本来更新本地的配置文件)。

 

我们在 config/path.js 文件中的 module.exports 内添加  appComponents: resolveApp('src/components') ,如:

module.exports = {
  ...
  appComponents: resolveApp('src/components'),
  ...
};

 

接下来,我们打开 config/webpack.config.js 文件,在 alias 对象中添加 "@components": paths.appComponents,如:

alias: {
  ...
  "@components": paths.appComponents,
  ...
}

 

然后,我们打开 tsconfig.json 文件,在 compilerOptions 对象中添加 ,如:

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

 

经过这三部设置后,你就可以在你的文件中通过 @components 别名访问到 src/components 文件夹了,如:

我们在 src/ 文件夹下面添加 pages/ 文件夹,然后再添加一个 home/ 文件夹,在 home 文件夹下面添加 index.tsx 文件。那么我们在 src/pages/home/index.tsx 文件里面可以使用  import Tab from '@components/Tabindex' 来引入 src/components/Tab/index.tsx 文件了。

 

tsconfig.json 配置文件说明博客:https://www.imooc.com/article/305339?block_id=tuijian_wz

posted @ 2021-01-03 11:28  破男孩  阅读(924)  评论(0编辑  收藏  举报