以Vuex为例,只要提供generator能力,我们就能使用插件化的能力给解析好
generator/index.js
- vue-cli
- packages
- @vue
- cli-plugin-vuex
- generator
- index.js
- generator
- cli-plugin-vuex
- @vue
- packages
store/index.js
- vue-cli
- packages
- @vue
- cli-plugin-vuex
- generator
- template-vue3
- src
- store
- index.js
- store
- src
- template-vue3
- generator
- cli-plugin-vuex
- @vue
- packages
这里对应的就是Vue中Vuex的用法
import { createStore } from 'vuex'
export default createStore({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
})
- vue-cli
- packages
- @vue
- cli-plugin-vuex
- index.js
- cli-plugin-vuex
- @vue
- packages
这里是一个入口的返回
module.exports = (api, options = {}) => {}
目的就是能够使用插件化的能力将其引入进去
vue add vuex
使用这样的命令实现插件化的能力
插件化的能力怎么引入呢?
vue add vuex
- vue-cli
- packages
- @vue
- cli
- bin
- vue.js
- bin
- cli
- @vue
- packages
add是通过引入lib下的add文件来添加插件的
program
.command('add <plugin> [pluginOptions]')
.description('install a plugin and invoke its generator in an already created project')
.option('--registry <url>', 'Use specified npm registry when installing dependencies (only for npm)')
.allowUnknownOption()
.action((plugin) => {
require('../lib/add')(plugin, minimist(process.argv.slice(3)))
})
add这里就是安装一个npm包的过程
- vue-cli
- packages
- @vue
- cli
- lib
- add.js
- lib
- cli
- @vue
- packages
- 判断service的package.json
const servicePkg = loadModule('@vue/cli-service/package.json', context)
if (servicePkg && semver.satisfies(servicePkg.version, '3.x')) {
// special internal "plugins"
if (/^(@vue\/)?router$/.test(pluginToAdd)) {
return addRouter(context)
}
if (/^(@vue\/)?vuex$/.test(pluginToAdd)) {
return addVuex(context)
}
}
- 安装上面说到的service的包
log()
log(`???? Installing ${chalk.cyan(packageName)}...`)
log()
const pm = new PackageManager({ context })
if (pluginVersion) {
await pm.add(`${packageName}@${pluginVersion}`)
} else if (isOfficialPlugin(packageName)) {
const { latestMinor } = await getVersions()
await pm.add(`${packageName}@~${latestMinor}`)
} else {
await pm.add(packageName, { tilde: true })
}
- 然后找目录下的generator,生成generator目录下的文件
log(`${chalk.green('✔')} Successfully installed plugin: ${chalk.cyan(packageName)}`)
log()
const generatorPath = resolveModule(`${packageName}/generator`, context)
if (generatorPath) {
invoke(pluginName, options, context)
} else {
log(`Plugin ${packageName} does not have a generator to invoke`)
}