开发 JavaScript 时,你有没有遇到过这样的状况。
页面复用大量共通组件,这些共通组件大致都在同一个文件夹下。可是因为组件分割和文件夹层级较深的缘故,你尝尝会写出👇这样的代码。前端
// some.js import VodMediaPlayer from '../../../components/VodVideo/VodMediaPlayer' import VideoInfo from '../../../components/VodVideo/VideoInfo' import RecommendList from '../../../components/RecommendList/RecommendList' import Comment from '../../../components/Comment/Comment' import { get, mediaPath } from '../../../util/fetch' import { API_VIDEO, API_CHANNEL } from '../../../util/constants'
你知道本身在键盘上敲击 ../
../../
../../../
时浪费了多少时间吗?react
时间就是金钱。 ~名言
为了解决这种问题,主流的前端工具都给出了解决方案。
本文介绍如何使用 babel plugin 的解决方案。git
首先咱们选择 babel-plugin-module-resolver。github
$ npm install --save-dev babel-plugin-module-resolver
{ "presets": ["env", "react"], "plugins": [ ["module-resolver", { "root": ["./"], "alias": { "components": "./src/components", "util": "./src/util" } }] }
这时你的代码能够修改成👇npm
// some.js import VodMediaPlayer from 'components/VodVideo/VodMediaPlayer' import VideoInfo from 'components/VodVideo/VideoInfo' import RecommendList from 'components/RecommendList/RecommendList' import Comment from 'components/Comment/Comment' import { get, mediaPath } from 'util/fetch' import { API_VIDEO, API_CHANNEL } from 'util/constants'
⚠️注意: 若是你使用了 eslint,这时 eslint 会报错,由于它不能处理新的写法。json
咱们选择 eslint-import-resolver-babel-modulebabel
$ npm install --save-dev eslint-plugin-import eslint-import-resolver-babel-module
配置 .eslintrcide
"settings": { "import/resolver": { "babel-module": {} } }
⚠️注意: 这时 eslint 不会报错了, 可是你会发现你点击 import
后面的组件名, VSCode 不会自动跳转到组件定义。工具
{ "compilerOptions": { "baseUrl": ".", "paths": { "components/*": ["src/components/*"], "util/*": ["src/util/*"], "locales/*": ["src/locales/*"] } } }
到此为止,咱们终于能够 Say Goodbye to '../' '../../' '../../../'
了。fetch
https://github.com/parcel-bun...
https://github.com/tleunen/ba...
https://code.visualstudio.com...