不少时候咱们使用别人的库,都是经过 npm install,再简单的引入,就可使用了。css
1
2
|
import React from 'react'
import { connect } from 'react-redux'
|
那若是咱们本身写的组件库和工具 utils 类怎么办?若是你不熟悉别名的概念,一般会引入相对路径,它会变成这样。node
1
2
3
|
import { someConstant } from './../../config/constants'
import MyComponent from './../../../components/MyComponent'
import { digitUppercase } from './../../../utils'
|
若是是频繁的引用使用,这样的引用方式的确不是很优雅。接下来就告诉你经过别名的方式可使用绝对路径去引用本地本身写的组件和工具类。react
1
2
3
4
5
|
import React from 'react'
import { connect } from 'react-redux'
import { someConstant } from 'config/constants'
import MyComponent from 'components/MyComponent'
import { digitUppercase } from 'utils'
|
咱们须要在 Webpack, Jest, Babel 和 VSCode 对应的配置脚本中声明便可。webpack
对于这篇文章,假设一个应用程序结构以下:git
1
2
3
4
5
6
7
8
9
|
MyApp/
dist/
src/
config/
components/
utils/
jsconfig.json
package.json
webpack.config.js
|
不使用任何额外的插件,Webpack 容许经过配置中的 resolve.alias
属性导入别名模块。github
1
2
3
4
5
6
7
|
module.resolve = {
alias: {
config: path.resolve(__dirname, "..", "src", "config"),
components: path.resolve(__dirname, "..", "src", "components"),
utils: path.resolve(__dirname, "..", "src", "utils"),
}
}
|
反作用:当 Webpack 知道如何处理这些别名时,VSCode 却不会,像 Intellisense 这样的工具将没法工做。web
首先你要在项目中建立一个 jsconfig.json
(建议放在项目的根目录中)。typescript
你能够本身新建一个 json 文件修改文件名为 jsconfig.json
。或者若是你全局安装了 typescript
,那么在项目根目录执行 tsc --init
便可生成一个 tsconfig.json
而后修改成 jsconfig.json
便可。根据文档上说 jsconfig.json
是默认开启了 "allowJs": true
的 tsconfig.json
,因此直接用 tsc --init
生成一个,这样全部配置都会带有注释说明。npm
更多详细配置请看 官网文档 jsconfig.json。json
最后记得重启下 VS Code 使其生效。
经过告诉 VS Code 如何理解这些别名可让它变得“更聪明”,就像在 jsconfig.json
文件中使用 exclude
属性,能够在搜索的时候排除 node_modules
或编译的文件夹(如 dist
)来加快 VS Code 的全局搜索速度。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
{
"compilerOptions": {
"target": "ES6",
"jsx": "react",
"experimentalDecorators": true,
"baseUrl": ".",
"paths": {
"components/*": ["src/components/*"],
"config/*": ["src/config/*"],
"utils/*": ["src/utils/*"]
}
},
"exclude": ["node_modules, "dist""]
}
|
须要安装插件Path Intellisense
,而且进行配置(项目或者全局的settings.json
):
1
2
3
4
5
|
"path-intellisense.mappings": {
"config": "${workspaceRoot}/src/config",
"component": "${workspaceRoot}/src/component",
"utils": "${workspaceRoot}/src/utils"
}
|
使用路径的就能够智能提醒路径,按住 ⌘command
就能够跳转到对应代码了。
babel-plugin-module-resolver
是一个 Babel 模块解析插件,在 babelrc 中能够配置模块的导入搜索路径为模块添加一个新的解析器。这个插件容许你添加新的 “根” 目录,这些目录包含你的模块。它还容许您设置一个自定义别名目录,具体的文件,甚至其余 NPM 模块。
若是你要安装它,根据如下步骤就能够了:
1
|
npm install --save-dev babel-plugin-module-resolver
|
安装完成之后,咱们在项目的根目录下,新建一个 .babelrc
配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
const path = require('path');
module.exports = {
plugins: [
[
'module-resolver',
{
alias: {
components: path.join(__dirname, './src/components'),
},
},
],
[
'import',
{
libraryName: 'antd',
style: true, // or 'css'
},
],
],
};
|