不少時候咱們使用別人的庫,都是經過 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'
},
],
],
};
|