Skip to content

Commit

Permalink
docs: improve documentation for plugin development
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Feb 6, 2018
1 parent 920d8fa commit e597d12
Show file tree
Hide file tree
Showing 5 changed files with 332 additions and 51 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

> This is the branch for `@vue/cli` 3.0.
**Status: alpha**
## Status: alpha

Certain combinations of plugins may not work properly, and things may break until we reach beta phase. Do not use in production yet unless you are adventurous.

## Install

Expand Down
132 changes: 111 additions & 21 deletions docs/Plugin.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
# Plugin Development Guide

#### Important Development Note

A plugin with a generator that injects additional dependencies other than packages in this repo (e.g. `chai` is injected by `@vue/cli-plugin-unit-mocha/generator/index.js`) should have those dependencies listed in its own `devDependencies` field. This ensures that:

1. the package always exist in this repo's root `node_modules` so that we don't have to reinstall them on every test.

2. `yarn.lock` stays consistent so that CI can better use it for inferring caching behavior.

## Core Concepts

- [Creator](#creator)
- [Service](#service)
- [CLI Plugin](#cli-plugin)
- [Service Plugin](#service-plugin)
- [Generator](#generator)
- [Prompts](#prompts)

There are two major parts of the system:

- `@vue/cli`: globally installed, exposes the `vue create <app>` command;
Expand All @@ -25,17 +24,36 @@ Both utilize a plugin-based architecture.

[Service][service-class] is the class created when invoking `vue-cli-service <command> [...args]`. Responsible for managing the internal webpack configuration, and exposes commands for serving and building the project.

### Plugin
### CLI Plugin

A CLI plugin is an npm package that can add additional features to a `@vue/cli` project. It should always contain a [Service Plugin](#service-plugin) as its main export, and can optionally contain a [Generator](#generator) and a [Prompt File](#prompts-for-3rd-party-plugins).

A typical CLI plugin's folder structure looks like the following:

```
.
├── README.md
├── generator.js # generator (optional)
├── prompts.js # prompts file (optional)
├── index.js # service plugin
└── package.json
```

### Service Plugin

Service plugins are loaded automatically when a Service instance is created - i.e. every time the `vue-cli-service` command is invoked inside a project.

Plugins are locally installed into the project as dependencies. `@vue/cli-service`'s [built-in commands][commands] and [config modules][config] are also all implemented as plugins. This repo also contains a number of plugins that are published as individual packages.
Note the concept of a "service plugin" we are discussing here is narrower than that of a "CLI plugin", which is published as an npm package. The former only refers to a module that will be loaded by `@vue/cli-service` when it's initialized, and is usually a part of the latter.

A plugin should export a function which receives two arguments:
In addition, `@vue/cli-service`'s [built-in commands][commands] and [config modules][config] are also all implemented as service plugins.

A service plugin should export a function which receives two arguments:

- A [PluginAPI][plugin-api] instance

- Project local options specified in `vue.config.js`, or in the `"vue-cli"` field in `package.json`.
- An object containing project local options specified in `vue.config.js`, or in the `"vue-cli"` field in `package.json`.

The API allows plugins to extend/modify the internal webpack config for different environments and inject additional commands to `vue-cli-service`. Example:
The API allows service plugins to extend/modify the internal webpack config for different environments and inject additional commands to `vue-cli-service`. Example:

``` js
module.exports = (api, projectOptions) => {
Expand All @@ -54,29 +72,79 @@ module.exports = (api, projectOptions) => {
}
```

#### Environment Variables in Service Plugins

An important thing to note about env variables is knowing when they are resolved. Typically, a command like `vue-cli-service serve` or `vue-cli-service build` will always call `api.setMode()` as the first thing it does. However, this also means those env variables may not yet be available when a service plugin is invoked:

``` js
module.exports = api => {
process.env.NODE_ENV // may not be resolved yet

api.regsiterCommand('build', () => {
api.setMode('production')
})
}
```

Instead, it's safer to rely on env variables in `configureWebpack` or `chainWebpack` functions, which are called lazily only when `api.resolveWebpackConfig()` is finally called:

``` js
module.exports = api => {
api.configureWebpack(config => {
if (process.env.NODE_ENV === 'production') {
// ...
}
})
}
```

#### Custom Options for 3rd Party Plugins

The exports from `vue.config.js` will be [validated against a schema](https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-service/lib/options.js#L3) to avoid typos and wrong config values. However, a 3rd party plugin can still allow the user to configure its behavior via the `pluginOptions` field. For example, with the following `vue.config.js`:

``` js
module.exports = {
pluginOptions: {
foo: { /* ... */ }
}
}
```

The 3rd party plugin can read `projectOptions.pluginOptions.foo` to determine conditional configurations.

### Generator

A plugin published as a package can also contain a `generator.js` or `generator/index.js` file. The generator inside a plugin will be invoked after the plugin is installed.
A CLI plugin published as a package can contain a `generator.js` or `generator/index.js` file. The generator inside a plugin will be invoked in two possible scenarios:

- During a project's initial creation, if the CLI plugin is installed as part of the project creation preset.

- When the plugin is installed after project's creation and invoked individually via `vue invoke`.

The [GeneratorAPI][generator-api] allows a generator to inject additional dependencies or fields into `package.json` and add files to the project.

A generator should export a function which receives three arguments:

1. A `GeneratorAPI` instance;

2. The generator options for this plugin. These options are resolved during the prompt phase of project creation, or loaded from a saved `~/.vuerc`. For example, if the saved `~/.vuerc` looks like this:
2. The generator options for this plugin. These options are resolved during the prompt phase of project creation, or loaded from a saved preset in `~/.vuerc`. For example, if the saved `~/.vuerc` looks like this:

``` json
{
"plugins": {
"@vue/cli-plugin-foo": { "option": "bar" }
"presets" : {
"foo": {
"plugins": {
"@vue/cli-plugin-foo": { "option": "bar" }
}
}
}
}
```

Then the plugin `@vue/cli-plugin-foo` will receive `{ option: 'bar' }` as its second argument.
And if the user creates a project using the `foo` preset, then the generator of `@vue/cli-plugin-foo` will receive `{ option: 'bar' }` as its second argument.

For a 3rd party plugin, the options will be resolved from the prompts or command line arguments when the user executes `vue invoke` (see [Prompts for 3rd Party Plugins](#prompts-for-3rd-party-plugins)).

3. The entire `.vuerc` object will be passed as the third argument.
3. The entire preset (`presets.foo`) will be passed as the third argument.

**Example:**

Expand All @@ -98,9 +166,11 @@ module.exports = (api, options, rootOptions) => {
}
```

### Prompt Modules
### Prompts

Currently, only built-in plugins have the ability to customize the prompts when creating a new project, and the prompt modules are located [inside the `@vue/cli` package][prompt-modules].
#### Prompts for Built-in Plugins

Only built-in plugins have the ability to customize the initial prompts when creating a new project, and the prompt modules are located [inside the `@vue/cli` package][prompt-modules].

A prompt module should export a function that receives a [PromptModuleAPI][prompt-api] instance. The prompts are presented using [inquirer](https://github.com/SBoudrias/Inquirer.js) under the hood:

Expand Down Expand Up @@ -133,6 +203,26 @@ module.exports = api => {
}
```

#### Prompts for 3rd Party Plugins

3rd party plugins are typically installed manually after a project is already created, and the user will initialize the plugin by calling `vue invoke`. If the plugin contains a `prompt.js` in its root directory, it will be used during invocation. The file should export an array of [Questions](https://github.com/SBoudrias/Inquirer.js#question) that will be handled by Inquirer.js. The resolved answers object will be passed to the plugin's generator as options.

Alternatively, the user can skip the prompts and directly initialize the plugin by passing options via the command line, e.g.:

``` sh
vue invoke my-plugin --mode awesome
```

## Note on Development of Core Plugins

> This section only applies if you are working on a built-in plugin inside this very repository.
A plugin with a generator that injects additional dependencies other than packages in this repo (e.g. `chai` is injected by `@vue/cli-plugin-unit-mocha/generator/index.js`) should have those dependencies listed in its own `devDependencies` field. This ensures that:

1. the package always exist in this repo's root `node_modules` so that we don't have to reinstall them on every test.

2. `yarn.lock` stays consistent so that CI can better use it for inferring caching behavior.

[creator-class]: https://github.com/vuejs/vue-cli/tree/dev/packages/@vue/cli/lib/Creator.js
[service-class]: https://github.com/vuejs/vue-cli/tree/dev/packages/@vue/cli-service/lib/Service.js
[generator-api]: https://github.com/vuejs/vue-cli/tree/dev/packages/@vue/cli/lib/GeneratorAPI.js
Expand Down
51 changes: 51 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,52 @@
# WIP

## Introduction

## The CLI

## Configuration

### Vue CLI options

### Modes and Environment Variables

### Webpack

- #### Basic Configuration

- #### Chaining

- #### Using Resolved Config as a File

### Babel

- link to: babel preset
- link to: babel plugin

### CSS

- #### PostCSS

- #### CSS Modules

- #### Other Pre-Processors

### ESLint

- link to: eslint plugin

### TypeScript

- link to: typescript plugin

### Unit Testing

- #### Jest

- #### Mocha (via `mocha-webpack`)

### E2E Testing

- #### Cypress

- #### Nightwatch
88 changes: 81 additions & 7 deletions packages/@vue/cli-service/lib/PluginAPI.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,45 @@
const path = require('path')

module.exports = class PluginAPI {
class PluginAPI {
/**
* @param {string} id - Id of the plugin.
* @param {Service} service - A vue-cli-service instance.
*/
constructor (id, service) {
this.id = id
this.service = service
}

/**
* Resolve path for a project.
*
* @param {string} _path - Relative path from project root
* @return {string} The resolved absolute path.
*/
resolve (_path) {
return path.resolve(this.service.context, _path)
}

/**
* Check if the project has a given plugin.
*
* @param {string} id - Plugin id, can omit the (@vue/|vue-)-cli-plugin- prefix
* @return {boolean}
*/
hasPlugin (id) {
const prefixRE = /^(@vue\/|vue-)cli-plugin-/
return this.service.plugins.some(p => {
return p.id === id || p.id.replace(prefixRE, '') === id
})
}

// set project mode.
// this should be called by any registered command as early as possible.
/**
* Set project mode and resolve env variables for that mode.
* this should be called by any registered command as early as possible, and
* should be called only once per command.
*
* @param {string} mode
*/
setMode (mode) {
process.env.VUE_CLI_MODE = mode
// by default, NODE_ENV and BABEL_ENV are set to "development" unless mode
Expand All @@ -31,6 +52,19 @@ module.exports = class PluginAPI {
this.service.loadEnv(mode)
}

/**
* Register a command that will become available as `vue-cli-service [name]`.
*
* @param {string} name
* @param {object} [opts]
* {
* description: string,
* usage: string,
* options: { [string]: string }
* }
* @param {function} fn
* (args: { [string]: string }, rawArgs: string[]) => ?Promise
*/
registerCommand (name, opts, fn) {
if (typeof opts === 'function') {
fn = opts
Expand All @@ -39,23 +73,63 @@ module.exports = class PluginAPI {
this.service.commands[name] = { fn, opts }
}

/**
* Regsiter a function that will receive a chainable webpack config
* the function is lazy and won't be called until `resolveWebpackConfig` is
* called
*
* @param {function} fn
*/
chainWebpack (fn) {
this.service.webpackChainFns.push(fn)
}

/**
* Regsiter
* - a webpack configuration object that will be merged into the config
* OR
* - a function that will receive the raw webpack config.
* the function can either mutate the config directly or return an object
* that will be merged into the config.
*
* @param {object | function} fn
*/
configureWebpack (fn) {
this.service.webpackRawConfigFns.push(fn)
}

/**
* Register a dev serve config function. It will receive the express `app`
* instnace of the dev server.
*
* @param {function} fn
*/
configureDevServer (fn) {
this.service.devServerConfigFns.push(fn)
}

/**
* Resolve the final raw webpack config, that will be passed to webpack.
* Typically, you should call `setMode` before calling this.
*
* @return {object} Raw webpack config.
*/
resolveWebpackConfig () {
return this.service.resolveWebpackConfig()
}

/**
* Resolve an intermediate chainable webpack config instance, which can be
* further tweaked before generating the final raw webpack config.
* You can call this multiple times to generate different branches of the
* base webpack config.
* See https://github.com/mozilla-neutrino/webpack-chain
*
* @return {ChainableWebpackConfig}
*/
resolveChainableWebpackConfig () {
return this.service.resolveChainableWebpackConfig()
}

configureDevServer (fn) {
this.service.devServerConfigFns.push(fn)
}
}

module.exports = PluginAPI
Loading

0 comments on commit e597d12

Please sign in to comment.