code:
## @vue/babel-sugar-composition-api-render-instance

> Ported from [luwanquan/babel-preset-vca-jsx](https://github.com/luwanquan/babel-preset-vca-jsx) by [@luwanquan](https://github.com/luwanquan)

Babel syntactic sugar for replacing `this` with `getCurrentInstance()` in Vue JSX with @vue/composition-api

### Babel Compatibility Notes

- This repo is only compatible with Babel 7.x

### Usage

Install the dependencies:

```sh
# for yarn:
yarn add @vue/babel-sugar-composition-api-render-instance
# for npm:
npm install @vue/babel-sugar-composition-api-render-instance --save
```

In your `.babelrc`:

```json
{
  "plugins": ["@vue/babel-sugar-composition-api-render-instance"]
}
```

However it is recommended to use the [configurable preset](../babel-preset-jsx/README.md) instead.

### Details

This plugin automatically replaces `this` in `setup()` with `getCurrentInstance()`. This is required for JSX to work in @vue/composition-api as `this` is not available in `setup()`

Input:

```jsx
defineComponent({
  setup() {
    return () => <MyComponent vModel={a.b} />
  }
})
```

Output (without @vue/babel-sugar-composition-api-render-instance):

```jsx
defineComponent({
  setup() {
    return () => <MyComponent model={{
      value: a.b,
      callback: $$v => {
        this.$set(a, "b", $$v);
      }
    }} />
  }
})
```

Output (with @vue/babel-sugar-composition-api-render-instance):

```jsx
import { getCurrentInstance } from "@vue/composition-api";

defineComponent({
  setup() {
    const __currentInstance = getCurrentInstance();

    return () => <MyComponent model={{
      value: a.b,
      callback: $$v => {
        __currentInstance.$set(a, "b", $$v);
      }
    }} />
  }
})
```


description: Babel syntactic sugar for replaceing `this` with `getCurrentInstance()` in Vue JSX with @vue/composition-api

author: luwanquan <luwanquan@f-road.com.cn>

license: MIT

access: public

prepublish: yarn build

build: rollup -c

build:test: rollup -c rollup.config.testing.js

pretest: yarn build:test && cd ../babel-sugar-v-model && yarn build:test

test: nyc --reporter=html --reporter=text-summary ava -v test/test.js

exclude: dist test

license: mit


code:
## @vue/babel-sugar-functional-vue

Syntactic sugar for functional components.

### Babel Compatibility Notes

- This repo is only compatible with Babel 7.x, for 6.x please use [vuejs/babel-plugin-transform-vue-jsx](https://github.com/vuejs/babel-plugin-transform-vue-jsx)

### Usage

Install the dependencies:

```sh
# for yarn:
yarn add @vue/babel-sugar-functional-vue
# for npm:
npm install @vue/babel-sugar-functional-vue --save
```

In your `.babelrc`:

```json
{
  "plugins": ["@vue/babel-sugar-functional-vue"]
}
```

However it is recommended to use the [configurable preset](../babel-preset-jsx/README.md) instead.

### Details

This plugin transpiles arrow functions that return JSX into functional components but only if it's an uppercase variable declaration or default export:

```js
// Original:
export const A = ({ props, listeners }) => <div onClick={listeners.click}>{props.msg}</div>
export const b = ({ props, listeners }) => <div onClick={listeners.click}>{props.msg}</div>
export default ({ props, listeners }) => <div onClick={listeners.click}>{props.msg}</div>

// Result:
export const A = {
  functional: true,
  render: (h, {
    props,
    listeners
  }) => <div onClick={listeners.click}>{props.msg}</div>
}
export const b = ({ props, listeners }) => <div onClick={listeners.click}>{props.msg}</div>
export default {
  functional: true,
  render: (h, {
    props,
    listeners
  }) => <div onClick={listeners.click}>{props.msg}</div>
}
```


code:
"use strict";function _interopDefault(a){return a&&"object"==typeof a&&"default"in a?a["default"]:a}var syntaxJsx=_interopDefault(require("@babel/plugin-syntax-jsx"));/**
 * Check if expression is in method
 * @param t
 * @param path
 * @param parentLimitPath
 * @returns boolean
 */const isInMethod=(a,b,c)=>!!(b&&b!==c)&&(!!a.isObjectMethod(b)||isInMethod(a,b.parentPath,c)),hasJSX=(a,b)=>{let c=!1;return b.traverse({JSXElement(d){isInMethod(a,d,b)||(c=!0)}}),c},isFunctionalComponentDeclarator=(a,b)=>{const c=b.get("id.name").node[0];return!("A">c||"Z"<c)&&hasJSX(a,b)},convertFunctionalComponent=(a,b,c=null)=>{const d=[a.identifier("h"),...b.node.params],e=b.node.body,f=[a.objectProperty(a.identifier("functional"),a.booleanLiteral(!0)),a.objectProperty(a.identifier("render"),a.arrowFunctionExpression(d,e))];"development"===process.env.NODE_ENV&&c&&f.unshift(a.objectProperty(a.identifier("name"),a.stringLiteral(c))),b.replaceWith(a.objectExpression(f))};/**
 * Check path has JSX
 * @param t
 * @param path
 * @returns boolean
 */var index=a=>{const b=a.types;return{inherits:syntaxJsx,visitor:{Program(a){a.traverse({ExportDefaultDeclaration:{exit(a){b.isArrowFunctionExpression(a.node.declaration)&&hasJSX(b,a)&&convertFunctionalComponent(b,a.get("declaration"))}},VariableDeclaration:{exit(a){if(1===a.node.declarations.length&&b.isVariableDeclarator(a.node.declarations[0])&&b.isArrowFunctionExpression(a.node.declarations[0].init)){const c=a.get("declarations")[0];if(isFunctionalComponentDeclarator(b,c)){const c=a.node.declarations[0].id.name;convertFunctionalComponent(b,a.get("declarations")[0].get("init"),c)}}}}})}}}};module.exports=index;


@vue/babel-sugar-functional-vue

description: Babel syntactic sugar for functional components

pretest: yarn build:test && cd ../babel-plugin-transform-vue-jsx && yarn build:test


code:
## @vue/babel-sugar-inject-h

Syntactic sugar for automatic `h` inject in JSX.

### Babel Compatibility Notes

- This repo is only compatible with Babel 7.x, for 6.x please use [vuejs/babel-plugin-transform-vue-jsx](https://github.com/vuejs/babel-plugin-transform-vue-jsx)

### Usage

Install the dependencies:

```sh
# for yarn:
yarn add @vue/babel-sugar-inject-h
# for npm:
npm install @vue/babel-sugar-inject-h --save
```

In your `.babelrc`:

```json
{
  "plugins": ["@vue/babel-sugar-inject-h"]
}
```

However it is recommended to use the [configurable preset](../babel-preset-jsx/README.md) instead.

### Details

This plugin automatically injects `h` in every method that has JSX. By using this plugin you don't have to always specifically declare `h` as first parameter in your `render()` function.

```js
// Without @vue/babel-sugar-inject-h
export default {
  render (h) {
    return <button />
  }
}

// With @vue/babel-sugar-inject-h
export default {
  render () {
    return <button />
  }
}
```


@vue/babel-sugar-inject-h

description: Babel syntactic sugar for h automatic injection for Vue JSX


code:
## @vue/babel-sugar-v-model

Syntactic sugar for v-model in JSX.

### Babel Compatibility Notes

- This repo is only compatible with Babel 7.x, for 6.x please use [vuejs/babel-plugin-transform-vue-jsx](https://github.com/vuejs/babel-plugin-transform-vue-jsx)

### Usage

Install the dependencies:

```sh
# for yarn:
yarn add @vue/babel-sugar-v-model
# for npm:
npm install @vue/babel-sugar-v-model --save
```

In your `.babelrc`:

```json
{
  "plugins": ["@vue/babel-sugar-v-model"]
}
```

However it is recommended to use the [configurable preset](../babel-preset-jsx/README.md) instead.

### Details

This plugin adds v-model to the JSX and tries to mirror the same behaviour as in vue-template-compiler, with a few differences:

1.  You should use underscore (`_`) instead of dot (`.`) for modifiers (`vModel_trim={this.test}`)
2.  It is recommended to use camelCase version of it (`vModel`) in JSX, but you can use kebab-case too (`v-model`).

```js
export default {
  data: () => ({
    test: 'Hello World',
  }),
  render(h) {
    return (
      <div>
        <input type="text" vModel_trim={this.test} />
        {this.test}
      </div>
    )
  },
}
```


code:
declare namespace camelcase {
	interface Options {
		/**
		Uppercase the first character: `foo-bar` → `FooBar`.

		@default false
		*/
		readonly pascalCase?: boolean;
	}
}

declare const camelcase: {
	/**
	Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`.

	@param input - String to convert to camel case.

	@example
	```
	import camelCase = require('camelcase');

	camelCase('foo-bar');
	//=> 'fooBar'

	camelCase('foo_bar');
	//=> 'fooBar'

	camelCase('Foo-Bar');
	//=> 'fooBar'

	camelCase('Foo-Bar', {pascalCase: true});
	//=> 'FooBar'

	camelCase('--foo.bar', {pascalCase: false});
	//=> 'fooBar'

	camelCase('foo bar');
	//=> 'fooBar'

	console.log(process.argv[3]);
	//=> '--foo-bar'
	camelCase(process.argv[3]);
	//=> 'fooBar'

	camelCase(['foo', 'bar']);
	//=> 'fooBar'

	camelCase(['__foo__', '--bar'], {pascalCase: true});
	//=> 'FooBar'
	```
	*/
	(input: string | ReadonlyArray<string>, options?: camelcase.Options): string;

	// TODO: Remove this for the next major release, refactor the whole definition to:
	// declare function camelcase(
	// 	input: string | ReadonlyArray<string>,
	// 	options?: camelcase.Options
	// ): string;
	// export = camelcase;
	default: typeof camelcase;
};

export = camelcase;


code:
'use strict';

const preserveCamelCase = string => {
	let isLastCharLower = false;
	let isLastCharUpper = false;
	let isLastLastCharUpper = false;

	for (let i = 0; i < string.length; i++) {
		const character = string[i];

		if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) {
			string = string.slice(0, i) + '-' + string.slice(i);
			isLastCharLower = false;
			isLastLastCharUpper = isLastCharUpper;
			isLastCharUpper = true;
			i++;
		} else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) {
			string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
			isLastLastCharUpper = isLastCharUpper;
			isLastCharUpper = false;
			isLastCharLower = true;
		} else {
			isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;
			isLastLastCharUpper = isLastCharUpper;
			isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;
		}
	}

	return string;
};

const camelCase = (input, options) => {
	if (!(typeof input === 'string' || Array.isArray(input))) {
		throw new TypeError('Expected the input to be `string | string[]`');
	}

	options = Object.assign({
		pascalCase: false
	}, options);

	const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x;

	if (Array.isArray(input)) {
		input = input.map(x => x.trim())
			.filter(x => x.length)
			.join('-');
	} else {
		input = input.trim();
	}

	if (input.length === 0) {
		return '';
	}

	if (input.length === 1) {
		return options.pascalCase ? input.toUpperCase() : input.toLowerCase();
	}

	const hasUpperCase = input !== input.toLowerCase();

	if (hasUpperCase) {
		input = preserveCamelCase(input);
	}

	input = input
		.replace(/^[_.\- ]+/, '')
		.toLowerCase()
		.replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase())
		.replace(/\d+(\w|$)/g, m => m.toUpperCase());

	return postProcess(input);
};

module.exports = camelCase;
// TODO: Remove this for the next major release
module.exports.default = camelCase;


camelcase

description: Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`

repository: sindresorhus/camelcase

test: xo && ava && tsd

keywords: camelcase camel-case camel case dash hyphen dot underscore separator string text convert pascalcase pascal-case


code:
# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase)

> Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`

---

		Get professional support for 'camelcase' with a Tidelift subscription

		Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.

---

## Install

```
$ npm install camelcase
```

## Usage

```js
const camelCase = require('camelcase');

camelCase('foo-bar');
//=> 'fooBar'

camelCase('foo_bar');
//=> 'fooBar'

camelCase('Foo-Bar');
//=> 'fooBar'

camelCase('Foo-Bar', {pascalCase: true});
//=> 'FooBar'

camelCase('--foo.bar', {pascalCase: false});
//=> 'fooBar'

camelCase('foo bar');
//=> 'fooBar'

console.log(process.argv[3]);
//=> '--foo-bar'
camelCase(process.argv[3]);
//=> 'fooBar'

camelCase(['foo', 'bar']);
//=> 'fooBar'

camelCase(['__foo__', '--bar'], {pascalCase: true});
//=> 'FooBar'
```

## API

### camelCase(input, [options])

#### input

Type: `string` `string[]`

String to convert to camel case.

#### options

Type: `Object`

##### pascalCase

Type: `boolean`

Default: `false`

Uppercase the first character: `foo-bar` → `FooBar`

## Security

To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.

## Related

- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module
- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase
- [titleize](https://github.com/sindresorhus/titleize) - Capitalize every word in string
- [humanize-string](https://github.com/sindresorhus/humanize-string) - Convert a camelized/dasherized/underscored string into a humanized one

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code: area base br col embed hr img input link menuitem meta param source track wbr


code: a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd keygen label legend li link main map mark math menu menuitem meta meter nav noscript object ol optgroup option output p param picture pre progress q rb rp rt rtc ruby s samp script section select slot small source span strong style sub summary sup svg table tbody td template textarea tfoot th thead time title tr track u ul var video wbr


code:
'use strict';
module.exports = require('./html-tags.json');


html-tags

description: List of standard HTML tags

repository: sindresorhus/html-tags

test: xo && ava

keywords: html html5 tags elements list whatwg w3c void self-closing


code:
# html-tags [![Build Status](https://travis-ci.org/sindresorhus/html-tags.svg?branch=master)](https://travis-ci.org/sindresorhus/html-tags)

> List of standard HTML tags

It's just a couple of JSON files that can be used in any environment.

It intentionally leaves out obsolete tags.

## Install

```
$ npm install html-tags
```

## Usage

```js
const htmlTags = require('html-tags');

console.log(htmlTags);
//=> ['a', 'abbr', 'acronym', ...]
```

And void (self-closing) tags:

```js
const voidHtmlTags = require('html-tags/void');

console.log(voidHtmlTags);
//=> ['area', 'base', 'br', ...]
```

## License

MIT © [Sindre Sorhus](https://sindresorhus.com)


code:
'use strict';
module.exports = require('./html-tags-void.json');


@vue/babel-sugar-v-model

description: Babel syntactic sugar for v-model support in Vue JSX

pretest:snapshot: yarn build:test

test:snapshot: nyc --reporter=html --reporter=text-summary ava -v test/snapshot.js

build:dependency: cd ../babel-plugin-transform-vue-jsx && yarn build

pretest:functional: yarn build:dependency && yarn build:test && nyc --reporter=html --reporter=text-summary babel test/functional.js --plugins ./dist/plugin.testing.js,../babel-plugin-transform-vue-jsx/dist/plugin.js,@babel/plugin-transform-arrow-functions --out-file test/functional-compiled.js

test:functional: ava -v test/functional-compiled.js

test: rm -rf coverage* && yarn test:snapshot && mv coverage coverage-snapshot && yarn test:functional && mv coverage coverage-functional


code:
## @vue/babel-sugar-v-on

Syntactic sugar for v-on in JSX.

### Babel Compatibility Notes

- This repo is only compatible with Babel 7.x, for 6.x please use [vuejs/babel-plugin-transform-vue-jsx](https://github.com/vuejs/babel-plugin-transform-vue-jsx)

### Usage

Install the dependencies:

```sh
# for yarn:
yarn add @vue/babel-sugar-v-on
# for npm:
npm install @vue/babel-sugar-v-on --save
```

In your `.babelrc`:

```json
{
  "plugins": ["@vue/babel-sugar-v-on"]
}
```

However it is recommended to use the [configurable preset](../babel-preset-jsx/README.md) instead.

### Details

This plugin adds v-on to the JSX and tries to mirror the same behaviour as in vue-template-compiler, with a few differences:

1.  You should use underscore (`_`) instead of dot (`.`) for modifiers (`vOn:click_prevent={this.test}`)
2.  It is recommended to use camelCase version of it (`vOn`) in JSX, but you can use kebab-case too (`v-on`).

```js
export default {
  methods: {
    test() {
      console.log('Hello World')
    },
  },
  render(h) {
    return (
      <div>
        <a href="https://vuejs.org" vOn:click={this.test}>Vue</a>
      </div>
    )
  },
}
```


code:
# @vue/cli-overlay

> overlay for vue-cli


@vue/cli-overlay

description: error overlay & dev server middleware for vue-cli

type: git

keywords: vue cli cli-overlay

author: Evan You


code:
# @vue/cli-plugin-babel

> babel plugin for vue-cli

## Configuration

Uses Babel 7 + `babel-loader` + [@vue/babel-preset-app](https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/babel-preset-app) by default, but can be configured via `babel.config.js` to use any other Babel presets or plugins.

By default, `babel-loader` excludes files inside `node_modules` dependencies. If you wish to explicitly transpile a dependency module, you will need to add it to the `transpileDependencies` option in `vue.config.js`:

``` js
module.exports = {
  transpileDependencies: [
    // can be string or regex
    'my-dep',
    /other-dep/
  ]
}
```

## Caching

Cache options of [babel-loader](https://github.com/babel/babel-loader#options) is enabled by default and cache is stored in `<projectRoot>/node_modules/.cache/babel-loader`.

## Parallelization

[thread-loader](https://github.com/webpack-contrib/thread-loader) is enabled by default when the machine has more than 1 CPU cores. This can be turned off by setting `parallel: false` in `vue.config.js`.

`parallel` should be set to `false` when using Babel in combination with non-serializable loader options, such as regexes, dates and functions. These options would not be passed correctly to `babel-loader` which may lead to unexpected errors.

## Installing in an Already Created Project

```bash
vue add babel
```

## Injected webpack-chain Rules

- `config.rule('js')`
- `config.rule('js').use('babel-loader')`


code:
module.exports = function (fileInfo, api) {
  const j = api.jscodeshift
  const root = j(fileInfo.source)

  const useDoubleQuote = root.find(j.Literal).some(({ node }) => node.raw.startsWith('"'))

  root
    .find(j.Literal, { value: '@vue/app' })
    .replaceWith(j.stringLiteral('@vue/cli-plugin-babel/preset'))
  root
    .find(j.Literal, { value: '@vue/babel-preset-app' })
    .replaceWith(j.stringLiteral('@vue/cli-plugin-babel/preset'))

  const templateLiterals = root
    .find(j.TemplateLiteral, {
      expressions: { length: 0 }
    })

  templateLiterals
    .find(j.TemplateElement, {
      value: {
        cooked: '@vue/app'
      }
    })
    .closest(j.TemplateLiteral)
    .replaceWith(j.stringLiteral('@vue/cli-plugin-babel/preset'))

  templateLiterals
    .find(j.TemplateElement, {
      value: {
        cooked: '@vue/babel-preset-app'
      }
    })
    .closest(j.TemplateLiteral)
    .replaceWith(j.stringLiteral('@vue/cli-plugin-babel/preset'))

  return root.toSource({
    lineTerminator: '\n',
    quote: useDoubleQuote ? 'double' : 'single'
  })
}


code:
module.exports = api => {
  // Most likely you want to overwrite the whole config to ensure it's working
  // without conflicts, e.g. for a project that used Jest without Babel.
  // It should be rare for the user to have their own special babel config
  // without using the Babel plugin already.
  delete api.generator.files['babel.config.js']

  api.extendPackage({
    babel: {
      presets: ['@vue/cli-plugin-babel/preset']
    },
    vue: {
      transpileDependencies: true
    },
    dependencies: {
      'core-js': '^3.8.3'
    }
  })
}


code:
const path = require('path')
const babel = require('@babel/core')
const { isWindows } = require('@vue/cli-shared-utils')

function getDepPathRegex (dependencies) {
  const deps = dependencies.map(dep => {
    if (typeof dep === 'string') {
      const depPath = path.join('node_modules', dep, '/')
      return isWindows
        ? depPath.replace(/\\/g, '\\\\') // double escape for windows style path
        : depPath
    } else if (dep instanceof RegExp) {
      return dep.source
    }

    throw new Error('transpileDependencies only accepts an array of string or regular expressions')
  })
  return deps.length ? new RegExp(deps.join('|')) : null
}

/** @type {import('@vue/cli-service').ServicePlugin} */
module.exports = (api, options) => {
  const useThreads = process.env.NODE_ENV === 'production' && !!options.parallel
  const cliServicePath = path.dirname(require.resolve('@vue/cli-service'))

  // try to load the project babel config;
  // if the default preset is used,
  // there will be a VUE_CLI_TRANSPILE_BABEL_RUNTIME env var set.
  // the `filename` field is required
  // in case there're filename-related options like `ignore` in the user config
  babel.loadPartialConfigSync({ filename: api.resolve('src/main.js') })

  api.chainWebpack(webpackConfig => {
    webpackConfig.resolveLoader.modules.prepend(path.join(__dirname, 'node_modules'))

    const jsRule = webpackConfig.module
      .rule('js')
        .test(/\.m?jsx?$/)
        .exclude
          .add(filepath => {
            const SHOULD_SKIP = true
            const SHOULD_TRANSPILE = false

            // With data URI support in webpack 5, filepath could be undefined
            if (!filepath) {
              return SHOULD_SKIP
            }

            // Always transpile js in vue files
            if (/\.vue\.jsx?$/.test(filepath)) {
              return SHOULD_TRANSPILE
            }
            // Exclude dynamic entries from cli-service
            if (filepath.startsWith(cliServicePath)) {
              return SHOULD_SKIP
            }

            // To transpile `@babel/runtime`, the config needs to be
            // carefully adjusted to avoid infinite loops.
            // So we only do the tranpilation when the special flag is on.
            if (getDepPathRegex(['@babel/runtime']).test(filepath)) {
              return process.env.VUE_CLI_TRANSPILE_BABEL_RUNTIME
                ? SHOULD_TRANSPILE
                : SHOULD_SKIP
            }

            // if `transpileDependencies` is set to true, transpile all deps
            if (options.transpileDependencies === true) {
              // Some of the deps cannot be transpiled, though
              // https://stackoverflow.com/a/58517865/2302258
              const NON_TRANSPILABLE_DEPS = [
                'core-js',
                'webpack',
                'webpack-4',
                'css-loader',
                'mini-css-extract-plugin',
                'promise-polyfill',
                'html-webpack-plugin',
                'whatwg-fetch'
              ]
              const nonTranspilableDepsRegex = getDepPathRegex(NON_TRANSPILABLE_DEPS)
              return nonTranspilableDepsRegex.test(filepath) ? SHOULD_SKIP : SHOULD_TRANSPILE
            }

            // Otherwise, check if this is something the user explicitly wants to transpile
            if (Array.isArray(options.transpileDependencies)) {
              const transpileDepRegex = getDepPathRegex(options.transpileDependencies)
              if (transpileDepRegex && transpileDepRegex.test(filepath)) {
                return SHOULD_TRANSPILE
              }
            }

            // Don't transpile node_modules
            return /node_modules/.test(filepath) ? SHOULD_SKIP : SHOULD_TRANSPILE
          })
          .end()

    if (useThreads) {
      const threadLoaderConfig = jsRule
        .use('thread-loader')
          .loader(require.resolve('thread-loader'))

      if (typeof options.parallel === 'number') {
        threadLoaderConfig.options({ workers: options.parallel })
      }
    }

    jsRule
      .use('babel-loader')
        .loader(require.resolve('babel-loader'))
        .options({
          cacheCompression: false,
          ...api.genCacheConfig('babel-loader', {
            '@babel/core': require('@babel/core/package.json').version,
            '@vue/babel-preset-app': require('@vue/babel-preset-app/package.json').version,
            'babel-loader': require('babel-loader/package.json').version,
            modern: !!process.env.VUE_CLI_MODERN_BUILD,
            browserslist: api.service.pkg.browserslist
          }, [
            'babel.config.js',
            '.browserslistrc'
          ])
        })
  })
}


code:
const { chalk } = require('@vue/cli-shared-utils')

module.exports = api => {
  api.transformScript(
    'babel.config.js',
    require('../codemods/usePluginPreset')
  )

  if (api.fromVersion('^3')) {
    api.extendPackage(
      {
        dependencies: {
          'core-js': '^3.8.3'
        }
      },
      { warnIncompatibleVersions: false }
    )

    // TODO: implement a codemod to migrate polyfills
    api.exitLog(`core-js has been upgraded from v2 to v3.
If you have any custom polyfills defined in ${chalk.yellow('babel.config.js')}, please be aware their names may have been changed.
For more complete changelog, see https://github.com/zloirock/core-js/blob/master/CHANGELOG.md#300---20190319`)
  }
}


@vue/cli-plugin-babel

description: babel plugin for vue-cli

keywords: vue cli babel


code:
# @vue/cli-plugin-eslint

> eslint plugin for vue-cli

## Injected Commands

- **`vue-cli-service lint`**

  ```
  Usage: vue-cli-service lint [options] [...files]

  Options:

    --format [formatter] specify formatter (default: stylish)
    --no-fix             do not fix errors
    --max-errors         specify number of errors to make build failed (default: 0)
    --max-warnings       specify number of warnings to make build failed (default: Infinity)
    --output-file        specify file to write report to
  ```

Lints and fixes files. If no specific files are given, it lints all files in `src` and `tests`, as well as all JavaScript files in the root directory (these are most often config files such as `babel.config.js` or `.eslintrc.js`).

Other [ESLint CLI options](https://eslint.org/docs/user-guide/command-line-interface#options) are not supported.

::: tip
`vue-cli-service lint` will lint dotfiles `.*.js` by default. If you want to follow ESLint's default behavior instead, consider adding a `.eslintignore` file in your project.
:::

## Configuration

ESLint can be configured via `.eslintrc` or the `eslintConfig` field in `package.json`. See the [ESLint configuration docs](https://eslint.org/docs/user-guide/configuring) for more detail.

::: tip
The following option is under the section of [`vue.config.js`](https://cli.vuejs.org/config/#vue-config-js). It is respected only when `@vue/cli-plugin-eslint` is installed.
:::

Lint-on-save during development with `eslint-loader` is enabled by default. It can be disabled with the `lintOnSave` option in `vue.config.js`:

``` js
module.exports = {
  lintOnSave: false
}
```

When set to `true`, `eslint-loader` will emit lint errors as warnings. By default, warnings are only logged to the terminal and does not fail the compilation.

To make lint errors show up in the browser overlay, you can use `lintOnSave: 'error'`. This will force `eslint-loader` to always emit errors. this also means lint errors will now cause the compilation to fail.

Alternatively, you can configure the overlay to display both warnings and errors:

``` js
// vue.config.js
module.exports = {
  devServer: {
    overlay: {
      warnings: true,
      errors: true
    }
  }
}
```

When `lintOnSave` is a truthy value, `eslint-loader` will be applied in both development and production. If you want to disable `eslint-loader` during production build, you can use the following config:

``` js
// vue.config.js
module.exports = {
  lintOnSave: process.env.NODE_ENV !== 'production'
}
```

## Installing in an Already Created Project

```bash
vue add eslint
```

## Injected webpack-chain Rules

- `config.module.rule('eslint')`
- `config.module.rule('eslint').use('eslint-loader')`


code:
const DEPS_MAP = {
  base: {
    eslint: '^7.32.0',
    'eslint-plugin-vue': '^8.0.3'
  },
  airbnb: {
    '@vue/eslint-config-airbnb': '^6.0.0',
    'eslint-plugin-import': '^2.25.3',
    'eslint-plugin-vuejs-accessibility': '^1.1.0'
  },
  prettier: {
    'eslint-config-prettier': '^8.3.0',
    'eslint-plugin-prettier': '^4.0.0',
    prettier: '^2.4.1'
  },
  standard: {
    '@vue/eslint-config-standard': '^6.1.0',
    'eslint-plugin-import': '^2.25.3',
    'eslint-plugin-node': '^11.1.0',
    'eslint-plugin-promise': '^5.1.0'
  },
  typescript: {
    '@vue/eslint-config-typescript': '^9.1.0',
    '@typescript-eslint/eslint-plugin': '^5.4.0',
    '@typescript-eslint/parser': '^5.4.0'
  }
}

exports.DEPS_MAP = DEPS_MAP

exports.getDeps = function (api, preset, rootOptions = {}) {
  const deps = Object.assign({}, DEPS_MAP.base, DEPS_MAP[preset])

  if (api.hasPlugin('typescript')) {
    Object.assign(deps, DEPS_MAP.typescript)
  }

  if (api.hasPlugin('babel') && !api.hasPlugin('typescript')) {
    Object.assign(deps, {
      '@babel/eslint-parser': '^7.12.16',
      '@babel/core': '^7.12.16'
    })
  }

  return deps
}


code:
exports.config = (api, preset, rootOptions = {}) => {
  const config = {
    root: true,
    env: { node: true },
    extends: ['plugin:vue/essential'],
    parserOptions: {
      ecmaVersion: 2020
    },
    rules: {
      'no-console': makeJSOnlyValue(`process.env.NODE_ENV === 'production' ? 'warn' : 'off'`),
      'no-debugger': makeJSOnlyValue(`process.env.NODE_ENV === 'production' ? 'warn' : 'off'`)
    }
  }

  if (api.hasPlugin('babel') && !api.hasPlugin('typescript')) {
    config.parserOptions = {
      parser: '@babel/eslint-parser'
    }
  }

  if (preset === 'airbnb') {
    config.extends.push('@vue/airbnb')
  } else if (preset === 'standard') {
    config.extends.push('@vue/standard')
  } else if (preset === 'prettier') {
    config.extends.push(...['eslint:recommended', 'plugin:prettier/recommended'])
  } else {
    // default
    config.extends.push('eslint:recommended')
  }

  if (api.hasPlugin('typescript')) {
    // typically, typescript ruleset should be appended to the end of the `extends` array
    // but that is not the case for prettier, as there are conflicting rules
    if (preset === 'prettier') {
      config.extends.pop()
      config.extends.push(...['@vue/typescript/recommended', 'plugin:prettier/recommended'])
    } else {
      config.extends.push('@vue/typescript/recommended')
    }
  }

  if (rootOptions.vueVersion === '3') {
    const updateConfig = cfg =>
      cfg.replace(
        /plugin:vue\/(essential|recommended|strongly-recommended)/gi,
        'plugin:vue/vue3-$1'
      )
    config.extends = config.extends.map(updateConfig)
  }

  return config
}

// __expression is a special flag that allows us to customize stringification
// output when extracting configs into standalone files
function makeJSOnlyValue (str) {
  const fn = () => {}
  fn.__expression = str
  return fn
}

const baseExtensions = ['.js', '.jsx', '.vue']
exports.extensions = api => api.hasPlugin('typescript')
  ? baseExtensions.concat('.ts', '.tsx')
  : baseExtensions


code:
const fs = require('fs')
const path = require('path')

module.exports = (api, { config, lintOn = [] }, rootOptions, invoking) => {
  const eslintConfig = require('../eslintOptions').config(api, config, rootOptions)
  const devDependencies = require('../eslintDeps').getDeps(api, config, rootOptions)

  const pkg = {
    scripts: {
      lint: 'vue-cli-service lint'
    },
    eslintConfig,
    devDependencies
  }

  const editorConfigTemplatePath = path.resolve(__dirname, `./template/${config}/_editorconfig`)
  if (fs.existsSync(editorConfigTemplatePath)) {
    if (fs.existsSync(api.resolve('.editorconfig'))) {
      // Append to existing .editorconfig
      api.render(files => {
        const editorconfig = fs.readFileSync(editorConfigTemplatePath, 'utf-8')
        files['.editorconfig'] += `\n${editorconfig}`
      })
    } else {
      api.render(`./template/${config}`)
    }
  }

  if (typeof lintOn === 'string') {
    lintOn = lintOn.split(',')
  }

  if (!lintOn.includes('save')) {
    pkg.vue = {
      lintOnSave: false // eslint-loader configured in runtime plugin
    }
  }

  if (lintOn.includes('commit')) {
    Object.assign(pkg.devDependencies, {
      'lint-staged': '^11.1.2'
    })
    pkg.gitHooks = {
      'pre-commit': 'lint-staged'
    }
    const extensions = require('../eslintOptions').extensions(api)
      .map(ext => ext.replace(/^\./, '')) // remove the leading `.`
    pkg['lint-staged'] = {
      [`*.{${extensions.join(',')}}`]: 'vue-cli-service lint'
    }
  }

  api.extendPackage(pkg)

  // invoking only
  if (invoking) {
    if (api.hasPlugin('unit-mocha')) {
      // eslint-disable-next-line node/no-extraneous-require
      require('@vue/cli-plugin-unit-mocha/generator').applyESLint(api)
    } else if (api.hasPlugin('unit-jest')) {
      // eslint-disable-next-line node/no-extraneous-require
      require('@vue/cli-plugin-unit-jest/generator').applyESLint(api)
    }
  }

  // lint & fix after create to ensure files adhere to chosen config
  // for older versions that do not support the `hooks` feature
  try {
    api.assertCliVersion('^4.0.0-beta.0')
  } catch (e) {
    if (config && config !== 'base') {
      api.onCreateComplete(async () => {
        await require('../lint')({ silent: true }, api)
      })
    }
  }
}

// In PNPM v4, due to their implementation of the module resolution mechanism,
// put require('../lint') in the callback would raise a "Module not found" error,
// But we cannot cache the file outside the callback,
// because the node_module layout may change after the "intall additional dependencies"
// phase, thus making the cached module fail to execute.
// FIXME: at the moment we have to catch the bug and silently fail. Need to fix later.
module.exports.hooks = (api) => {
  // lint & fix after create to ensure files adhere to chosen config
  api.afterAnyInvoke(async () => {
    try {
      await require('../lint')({ silent: true }, api)
    } catch (e) {}
  })
}

// exposed for the typescript plugin
module.exports.applyTS = api => {
  api.extendPackage({
    eslintConfig: {
      extends: ['@vue/typescript'],
      parserOptions: {
        parser: '@typescript-eslint/parser'
      }
    },
    devDependencies: require('../eslintDeps').DEPS_MAP.typescript
  })
}


code:
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 100


code:
[*.{js,jsx,ts,tsx,vue}]
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true


code:
const path = require('path')
const eslintWebpackPlugin = require('eslint-webpack-plugin')

/** @type {import('@vue/cli-service').ServicePlugin} */
module.exports = (api, options) => {
  if (options.lintOnSave) {
    const extensions = require('./eslintOptions').extensions(api)
    // Use loadModule to allow users to customize their ESLint dependency version.
    const { resolveModule, loadModule } = require('@vue/cli-shared-utils')
    const cwd = api.getCwd()

    const eslintPkg =
      loadModule('eslint/package.json', cwd, true) ||
      loadModule('eslint/package.json', __dirname, true)

    // ESLint doesn't clear the cache when you upgrade ESLint plugins (ESlint do consider config changes)
    // so we have to manually generate a cache identifier that takes lock file into account.
    const { cacheIdentifier, cacheDirectory } = api.genCacheConfig(
      'eslint',
      {
        eslint: eslintPkg.version
      },
      ['package.json']
    )

    api.chainWebpack(webpackConfig => {
      const { lintOnSave } = options
      const treatAllAsWarnings = lintOnSave === true || lintOnSave === 'warning'
      const treatAllAsErrors = lintOnSave === 'error'

      const failOnWarning = treatAllAsErrors
      const failOnError = !treatAllAsWarnings

      /** @type {import('eslint-webpack-plugin').Options & import('eslint').ESLint.Options} */
      const eslintWebpackPluginOptions = {
        // common to both plugin and ESlint
        extensions,
        // ESlint options
        cwd,
        cache: true,
        cacheLocation: path.format({
          dir: cacheDirectory,
          name: process.env.VUE_CLI_TEST
            ? 'cache'
            : cacheIdentifier,
          ext: '.json'
        }),
        // plugin options
        context: cwd,

        failOnWarning,
        failOnError,

        eslintPath: path.dirname(
          resolveModule('eslint/package.json', cwd) ||
            resolveModule('eslint/package.json', __dirname)
        ),
        formatter: 'stylish'
      }
      webpackConfig.plugin('eslint').use(eslintWebpackPlugin, [eslintWebpackPluginOptions])
    })
  }

  api.registerCommand(
    'lint',
    {
      description: 'lint and fix source files',
      usage: 'vue-cli-service lint [options] [...files]',
      options: {
        '--format [formatter]': 'specify formatter (default: stylish)',
        '--no-fix': 'do not fix errors or warnings',
        '--no-fix-warnings': 'fix errors, but do not fix warnings',
        '--max-errors [limit]':
          'specify number of errors to make build failed (default: 0)',
        '--max-warnings [limit]':
          'specify number of warnings to make build failed (default: Infinity)',
        '--output-file [file_path]':
          'specify file to write report to'
      },
      details:
        'For more options, see https://eslint.org/docs/user-guide/command-line-interface#options'
    },
    async args => {
      await require('./lint')(args, api)
    }
  )
}


code:
const fs = require('fs')
const globby = require('globby')

const renamedArrayArgs = {
  ext: ['extensions'],
  rulesdir: ['rulePaths'],
  plugin: ['overrideConfig', 'plugins'],
  'ignore-pattern': ['overrideConfig', 'ignorePatterns']
}

const renamedObjectArgs = {
  env: { key: ['overrideConfig', 'env'], def: true },
  global: { key: ['overrideConfig', 'globals'], def: false }
}

const renamedArgs = {
  'inline-config': ['allowInlineConfig'],
  rule: ['overrideConfig', 'rules'],
  eslintrc: ['useEslintrc'],
  c: ['overrideConfigFile'],
  config: ['overrideConfigFile'],
  'output-file': ['outputFile']
}

module.exports = async function lint (args = {}, api) {
  const path = require('path')
  const cwd = api.resolve('.')
  const { log, done, exit, chalk, loadModule } = require('@vue/cli-shared-utils')
  const { ESLint } = loadModule('eslint', cwd, true) || require('eslint')
  const extensions = require('./eslintOptions').extensions(api)

  const argsConfig = normalizeConfig(args)
  const config = Object.assign({
    extensions,
    fix: true,
    cwd
  }, argsConfig)

  const noFixWarnings = (argsConfig.fixWarnings === false)
  const noFixWarningsPredicate = (lintResult) => lintResult.severity === 2
  config.fix = config.fix && (noFixWarnings ? noFixWarningsPredicate : true)

  if (!config.overrideConfig) {
    config.overrideConfig = {}
  }

  if (!fs.existsSync(api.resolve('.eslintignore')) && !config.overrideConfig.ignorePatterns) {
    // .eslintrc.js files (ignored by default)
    // However, we need to lint & fix them so as to make the default generated project's
    // code style consistent with user's selected eslint config.
    // Though, if users provided their own `.eslintignore` file, we don't want to
    // add our own customized ignore pattern here (in eslint, ignorePattern is
    // an addition to eslintignore, i.e. it can't be overridden by user),
    // following the principle of least astonishment.
    config.overrideConfig.ignorePatterns = [
      '!.*.js',
      '!{src,tests}/**/.*.js'
    ]
  }
  /** @type {import('eslint').ESLint} */
  const eslint = new ESLint(Object.fromEntries([

    // File enumeration
    'cwd',
    'errorOnUnmatchedPattern',
    'extensions',
    'globInputPaths',
    'ignore',
    'ignorePath',

    // Linting
    'allowInlineConfig',
    'baseConfig',
    'overrideConfig',
    'overrideConfigFile',
    'plugins',
    'reportUnusedDisableDirectives',
    'resolvePluginsRelativeTo',
    'rulePaths',
    'useEslintrc',

    // Autofix
    'fix',
    'fixTypes',

    // Cache-related
    'cache',
    'cacheLocation',
    'cacheStrategy'
  ].map(k => [k, config[k]])))

  const defaultFilesToLint = []

  for (const pattern of [
    'src',
    'tests',
    // root config files
    '*.js',
    '.*.js'
  ]) {
    if ((await Promise.all(globby
      .sync(pattern, { cwd, absolute: true })
      .map(p => eslint.isPathIgnored(p))))
      .some(r => !r)) {
      defaultFilesToLint.push(pattern)
    }
  }

  const files = args._ && args._.length
    ? args._
    : defaultFilesToLint

  // mock process.cwd before executing
  // See:
  // https://github.com/vuejs/vue-cli/issues/2554
  // https://github.com/benmosher/eslint-plugin-import/issues/602
  // https://github.com/eslint/eslint/issues/11218
  const processCwd = process.cwd
  if (!api.invoking) {
    process.cwd = () => cwd
  }
  const resultResults = await eslint.lintFiles(files)
  const reportErrorCount = resultResults.reduce((p, c) => p + c.errorCount, 0)
  const reportWarningCount = resultResults.reduce((p, c) => p + c.warningCount, 0)
  process.cwd = processCwd

  const formatter = await eslint.loadFormatter(args.format || 'stylish')

  if (config.outputFile) {
    const outputFilePath = path.resolve(config.outputFile)
    try {
      fs.writeFileSync(outputFilePath, formatter.format(resultResults))
      log(`Lint results saved to ${chalk.blue(outputFilePath)}`)
    } catch (err) {
      log(`Error saving lint results to ${chalk.blue(outputFilePath)}: ${chalk.red(err)}`)
    }
  }

  if (config.fix) {
    await ESLint.outputFixes(resultResults)
  }

  const maxErrors = argsConfig.maxErrors || 0
  const maxWarnings = typeof argsConfig.maxWarnings === 'number' ? argsConfig.maxWarnings : Infinity
  const isErrorsExceeded = reportErrorCount > maxErrors
  const isWarningsExceeded = reportWarningCount > maxWarnings

  if (!isErrorsExceeded && !isWarningsExceeded) {
    if (!args.silent) {
      const hasFixed = resultResults.some(f => f.output)
      if (hasFixed) {
        log(`The following files have been auto-fixed:`)
        log()
        resultResults.forEach(f => {
          if (f.output) {
            log(`  ${chalk.blue(path.relative(cwd, f.filePath))}`)
          }
        })
        log()
      }
      if (reportWarningCount || reportErrorCount) {
        console.log(formatter.format(resultResults))
      } else {
        done(hasFixed ? `All lint errors auto-fixed.` : `No lint errors found!`)
      }
    }
  } else {
    console.log(formatter.format(resultResults))
    if (isErrorsExceeded && typeof argsConfig.maxErrors === 'number') {
      log(`Eslint found too many errors (maximum: ${argsConfig.maxErrors}).`)
    }
    if (isWarningsExceeded) {
      log(`Eslint found too many warnings (maximum: ${argsConfig.maxWarnings}).`)
    }
    exit(1)
  }
}

function normalizeConfig (args) {
  const config = {}
  for (const key in args) {
    if (renamedArrayArgs[key]) {
      applyConfig(renamedArrayArgs[key], args[key].split(','))
    } else if (renamedObjectArgs[key]) {
      const obj = arrayToBoolObject(args[key].split(','), renamedObjectArgs[key].def)
      applyConfig(renamedObjectArgs[key].key, obj)
    } else if (renamedArgs[key]) {
      applyConfig(renamedArgs[key], args[key])
    } else if (key !== '_') {
      config[camelize(key)] = args[key]
    }
  }
  return config

  function applyConfig ([...keyPaths], value) {
    let targetConfig = config
    const lastKey = keyPaths.pop()
    for (const k of keyPaths) {
      targetConfig = targetConfig[k] || (targetConfig[k] = {})
    }
    targetConfig[lastKey] = value
  }

  function arrayToBoolObject (array, defaultBool) {
    const object = {}
    for (const element of array) {
      const [key, value] = element.split(':')
      object[key] = value != null ? value === 'true' : defaultBool
    }
    return object
  }
}

function camelize (str) {
  return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : '')
}


code:
const { semver } = require('@vue/cli-shared-utils')

/** @param {import('@vue/cli/lib/MigratorAPI')} api MigratorAPI */
module.exports = async (api) => {
  const pkg = require(api.resolve('package.json'))

  let localESLintRange = pkg.devDependencies.eslint

  // if project is scaffolded by Vue CLI 3.0.x or earlier,
  // the ESLint dependency (ESLint v4) is inside @vue/cli-plugin-eslint;
  // in Vue CLI v4 it should be extracted to the project dependency list.
  if (api.fromVersion('^3') && !localESLintRange) {
    localESLintRange = '^4.19.1'
    api.extendPackage({
      devDependencies: {
        eslint: localESLintRange,
        '@babel/eslint-parser': '^7.12.16',
        'eslint-plugin-vue': '^4.5.0'
      }
    })
  }

  const localESLintMajor = semver.major(
    semver.maxSatisfying(['4.99.0', '5.99.0', '6.99.0', '7.99.0'], localESLintRange) ||
      // in case the user does not specify a typical caret range;
      // it is used as **fallback** because the user may have not previously
      // installed eslint yet, such as in the case that they are from v3.0.x
      // eslint-disable-next-line node/no-extraneous-require
      require('eslint/package.json').version
  )

  if (localESLintMajor > 6) {
    return
  }

  const { getDeps } = require('../eslintDeps')

  const newDeps = getDeps(api)
  if (pkg.devDependencies['@vue/eslint-config-airbnb']) {
    Object.assign(newDeps, getDeps(api, 'airbnb'))
  }
  if (pkg.devDependencies['@vue/eslint-config-standard']) {
    Object.assign(newDeps, getDeps(api, 'standard'))
  }
  if (pkg.devDependencies['@vue/eslint-config-prettier']) {
    Object.assign(newDeps, getDeps(api, 'prettier'))
  }

  const fields = { devDependencies: newDeps }

  if (newDeps['@babel/core'] && newDeps['@babel/eslint-parser']) {
    Reflect.deleteProperty(api.generator.pkg.devDependencies, 'babel-eslint')

    const minSupportedBabelCoreVersion = '>=7.2.0'
    const localBabelCoreVersion = pkg.devDependencies['@babel/core']

    if (localBabelCoreVersion &&
      semver.satisfies(
        localBabelCoreVersion,
        minSupportedBabelCoreVersion
      )) {
      Reflect.deleteProperty(newDeps, '@babel/core')
    }

    fields.eslintConfig = {
      parserOptions: {
        parser: '@babel/eslint-parser'
      }
    }
  }

  api.extendPackage(fields, { warnIncompatibleVersions: false })

  // in case anyone's upgrading from the legacy `typescript-eslint-parser`
  if (api.hasPlugin('typescript')) {
    api.extendPackage({
      eslintConfig: {
        parserOptions: {
          parser: '@typescript-eslint/parser'
        }
      }
    })
  }

  api.exitLog(`ESLint upgraded from v${localESLintMajor}. to v7\n`)

  // TODO:
  // transform `@vue/prettier` to `eslint:recommended` + `plugin:prettier/recommended`
  // remove `@vue/prettier/@typescript-eslint`
  // transform `@vue/typescript` to `@vue/typescript/recommended` and also fix prettier compatibility for it
}


@vue/cli-plugin-eslint

description: eslint plugin for vue-cli

keywords: vue cli eslint


code:
// these prompts are used if the plugin is late-installed into an existing
// project and invoked by `vue invoke`.

const { chalk, hasGit } = require('@vue/cli-shared-utils')

module.exports = [
  {
    name: 'config',
    type: 'list',
    message: `Pick an ESLint config:`,
    choices: [
      {
        name: 'Error prevention only',
        value: 'base',
        short: 'Basic'
      },
      {
        name: 'Airbnb',
        value: 'airbnb',
        short: 'Airbnb'
      },
      {
        name: 'Standard',
        value: 'standard',
        short: 'Standard'
      },
      {
        name: 'Prettier',
        value: 'prettier',
        short: 'Prettier'
      }
    ]
  },
  {
    name: 'lintOn',
    type: 'checkbox',
    message: 'Pick additional lint features:',
    choices: [
      {
        name: 'Lint on save',
        value: 'save',
        checked: true
      },
      {
        name: 'Lint and fix on commit' + (hasGit() ? '' : chalk.red(' (requires Git)')),
        value: 'commit'
      }
    ]
  }
]


code:
const CONFIG = 'org.vue.eslintrc'

const CATEGORIES = [
  'essential',
  'strongly-recommended',
  'recommended',
  'uncategorized'
]

const DEFAULT_CATEGORY = 'essential'
const RULE_SETTING_OFF = 'off'
const RULE_SETTING_ERROR = 'error'
const RULE_SETTING_WARNING = 'warn'
const RULE_SETTINGS = [RULE_SETTING_OFF, RULE_SETTING_ERROR, RULE_SETTING_WARNING]

const defaultChoices = [
  {
    name: 'org.vue.eslint.config.eslint.setting.off',
    value: JSON.stringify(RULE_SETTING_OFF)
  },
  {
    name: 'org.vue.eslint.config.eslint.setting.error',
    value: JSON.stringify(RULE_SETTING_ERROR)
  },
  {
    name: 'org.vue.eslint.config.eslint.setting.warning',
    value: JSON.stringify(RULE_SETTING_WARNING)
  }
]

function escapeHTML (text) {
  return text.replace(/</g, '<').replace(/>/g, '>')
}

function getEslintConfigName (eslint) {
  let config = eslint.extends

  if (eslint.extends instanceof Array) {
    config = eslint.extends.find(configName => configName.startsWith('plugin:vue/'))
  }

  return config && config.startsWith('plugin:vue/') ? config : null
}

// Sets default value regarding selected global config
function getDefaultValue (rule, data) {
  const { category: ruleCategory } = rule.meta.docs
  const currentCategory = getEslintConfigName(data.eslint)

  if (!currentCategory || ruleCategory === undefined) return RULE_SETTING_OFF

  return CATEGORIES.indexOf(ruleCategory) <= CATEGORIES.indexOf(currentCategory.split('/')[1])
    ? RULE_SETTING_ERROR
    : RULE_SETTING_OFF
}

function getEslintPrompts (data, rules) {
  const allRules = Object.keys(rules)
    .map(ruleKey => ({
      ...rules[ruleKey],
      name: `vue/${ruleKey}`
    }))

  return CATEGORIES
    .map(category =>
      allRules.filter(rule =>
        rule.meta.docs.category === category || (
          category === 'uncategorized' &&
          rule.meta.docs.category === undefined
        )
      )
    )
    .reduce((acc, rulesArr) => [...acc, ...rulesArr], [])
    .map(rule => {
      const value = data.eslint &&
        data.eslint.rules &&
        data.eslint.rules[rule.name]

      return {
        name: rule.name,
        type: 'list',
        message: rule.name,
        group: `org.vue.eslint.config.eslint.groups.${rule.meta.docs.category || 'uncategorized'}`,
        description: escapeHTML(rule.meta.docs.description),
        link: rule.meta.docs.url,
        default: JSON.stringify(getDefaultValue(rule, data)),
        value: JSON.stringify(value),
        choices: !value || RULE_SETTINGS.indexOf(value) > -1
          ? defaultChoices
          : [...defaultChoices, {
            name: 'org.vue.eslint.config.eslint.setting.custom',
            value: JSON.stringify(value)
          }]
      }
    })
}

function onRead ({ data, cwd }) {
  const { loadModule } = require('@vue/cli-shared-utils')
  const rules = loadModule('eslint-plugin-vue', cwd, true).rules

  return {
    tabs: [
      {
        id: 'general',
        label: 'org.vue.eslint.config.eslint.general.label',
        prompts: [
          {
            name: 'lintOnSave',
            type: 'confirm',
            message: 'org.vue.eslint.config.eslint.general.lintOnSave.message',
            description: 'org.vue.eslint.config.eslint.general.lintOnSave.description',
            link: 'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint#configuration',
            default: true,
            value: data.vue && data.vue.lintOnSave
          },
          {
            name: 'config',
            type: 'list',
            message: 'org.vue.eslint.config.eslint.general.config.message',
            description: 'org.vue.eslint.config.eslint.general.config.description',
            link: 'https://github.com/vuejs/eslint-plugin-vue',
            default: `plugin:vue/${DEFAULT_CATEGORY}`,
            choices: CATEGORIES.filter(category => category !== 'uncategorized').map(category => ({
              name: `org.vue.eslint.config.eslint.groups.${category}`,
              value: `plugin:vue/${category}`
            })),
            value: getEslintConfigName(data.eslint)
          }
        ]
      },
      {
        id: 'rules',
        label: 'org.vue.eslint.config.eslint.rules.label',
        prompts: getEslintPrompts(data, rules)
      }
    ]
  }
}

async function onWrite ({ data, api, prompts }) {
  const eslintData = { ...data.eslint }
  const vueData = {}
  for (const prompt of prompts) {
    // eslintrc
    if (prompt.id === 'config') {
      if (eslintData.extends instanceof Array) {
        const vueEslintConfig = eslintData.extends.find(config => config.indexOf('plugin:vue/') === 0)
        const index = eslintData.extends.indexOf(vueEslintConfig)
        eslintData.extends[index] = JSON.parse(prompt.value)
      } else {
        eslintData.extends = JSON.parse(prompt.value)
      }
    } else if (prompt.id.indexOf('vue/') === 0) {
      eslintData[`rules.${prompt.id}`] = await api.getAnswer(prompt.id, JSON.parse)
    } else {
      // vue.config.js
      vueData[prompt.id] = await api.getAnswer(prompt.id)
    }
  }
  api.setData('eslint', eslintData)
  api.setData('vue', vueData)
}

const config = {
  id: CONFIG,
  name: 'ESLint configuration',
  description: 'org.vue.eslint.config.eslint.description',
  link: 'https://github.com/vuejs/eslint-plugin-vue',
  files: {
    eslint: {
      js: ['.eslintrc.js'],
      json: ['.eslintrc', '.eslintrc.json'],
      yaml: ['.eslintrc.yaml', '.eslintrc.yml'],
      package: 'eslintConfig'
    },
    vue: {
      js: ['vue.config.js']
    }
  },
  onRead,
  onWrite
}

module.exports = {
  config,
  getEslintConfigName,
  getDefaultValue,
  getEslintPrompts
}


code:
const configDescriptor = require('./configDescriptor')
const taskDescriptor = require('./taskDescriptor')

const CONFIG = 'org.vue.eslintrc'
const OPEN_ESLINTRC = 'org.vue.eslint.open-eslintrc'

module.exports = api => {
  api.describeConfig(configDescriptor.config)
  api.describeTask(taskDescriptor.task)

  api.onViewOpen(({ view }) => {
    if (view.id !== 'vue-project-configurations') {
      removeSuggestions()
    }
  })

  api.onConfigRead(({ config }) => {
    if (config.id === CONFIG) {
      api.addSuggestion({
        id: OPEN_ESLINTRC,
        type: 'action',
        label: 'org.vue.eslint.suggestions.open-eslintrc.label',
        handler () {
          const file = config.foundFiles.eslint.path
          const { launch } = require('@vue/cli-shared-utils')
          launch(file)
          return {
            keep: true
          }
        }
      })
    } else {
      removeSuggestions()
    }
  })

  function removeSuggestions () {
    [OPEN_ESLINTRC].forEach(id => api.removeSuggestion(id))
  }
}


code:
const task = {
  match: /vue-cli-service lint/,
  description: 'org.vue.eslint.tasks.lint.description',
  link: 'https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint#injected-commands',
  prompts: [
    {
      name: 'noFix',
      type: 'confirm',
      default: false,
      description: 'org.vue.eslint.tasks.lint.noFix'
    }
  ],
  onBeforeRun: ({ answers, args }) => {
    if (answers.noFix) args.push('--no-fix')
  }
}

module.exports = {
  task
}


code:
# @vue/cli-plugin-router

> router plugin for vue-cli

## Installing in an Already Created Project

```bash
vue add router
```


code:
module.exports = (api, options = {}, rootOptions = {}) => {
  const isVue3 = (rootOptions.vueVersion === '3')

  api.injectImports(api.entryFile, `import router from './router'`)

  if (isVue3) {
    api.transformScript(api.entryFile, require('./injectUseRouter'))
    api.extendPackage({
      dependencies: {
        'vue-router': '^4.0.3'
      }
    })
  } else {
    api.injectRootOptions(api.entryFile, `router`)

    api.extendPackage({
      dependencies: {
        'vue-router': '^3.5.1'
      }
    })
  }

  api.render('./template', {
    historyMode: options.historyMode,
    doesCompile: api.hasPlugin('babel') || api.hasPlugin('typescript'),
    hasTypeScript: api.hasPlugin('typescript')
  })

  if (isVue3) {
    api.render('./template-vue3', {
      historyMode: options.historyMode,
      doesCompile: api.hasPlugin('babel') || api.hasPlugin('typescript'),
      hasTypeScript: api.hasPlugin('typescript')
    })
  }

  if (api.invoking) {
    if (api.hasPlugin('typescript')) {
      /* eslint-disable-next-line node/no-extraneous-require */
      const convertFiles = require('@vue/cli-plugin-typescript/generator/convert')
      convertFiles(api)
    }
  }
}


code:
module.exports = (file, api) => {
  const j = api.jscodeshift
  const root = j(file.source)

  const appRoots = root.find(j.CallExpression, (node) => {
    if (j.Identifier.check(node.callee) && node.callee.name === 'createApp') {
      return true
    }

    if (
      j.MemberExpression.check(node.callee) &&
      j.Identifier.check(node.callee.object) &&
      node.callee.object.name === 'Vue' &&
      j.Identifier.check(node.callee.property) &&
      node.callee.property.name === 'createApp'
    ) {
      return true
    }
  })

  appRoots.replaceWith(({ node: createAppCall }) => {
    return j.callExpression(
      j.memberExpression(createAppCall, j.identifier('use')),
      [j.identifier('router')]
    )
  })

  return root.toSource()
}


code:
---
extend: '@vue/cli-service/generator/template/src/App.vue'
replace:
  - !!js/regexp /<template>[^]*?<\/template>/
  - !!js/regexp /\n<script>[^]*?<\/script>\n/
  - !!js/regexp /  margin-top[^]*?<\/style>/
---

<%# REPLACE %>
<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </nav>
  <router-view/>
</template>
<%# END_REPLACE %>

<%# REPLACE %>
<%# END_REPLACE %>

<%# REPLACE %>
}

<%_ if (rootOptions.cssPreprocessor !== 'stylus') { _%>
  <%_ if (!rootOptions.cssPreprocessor) { _%>
nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
  <%_ } else { _%>
nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
  <%_ } _%>
<%_ } else { _%>
nav
  padding 30px
  a
    font-weight bold
    color #2c3e50
    &.router-link-exact-active
      color #42b983
<%_ } _%>
</style>
<%# END_REPLACE %>


code:
import { createRouter<%
  if (historyMode) {
    %>, createWebHistory<%
  } else {
    %>, createWebHashHistory<%
  }

  if (hasTypeScript) {
    %>, RouteRecordRaw<%
  }
  %> } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes<% if (hasTypeScript) { %>: Array<RouteRecordRaw><% } %> = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    <%_ if (doesCompile) { _%>
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
    <%_ } else { _%>
    component: function () {
      return import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
    }
    <%_ } _%>
  }
]

const router = createRouter({
  <%_ if (historyMode) { _%>
  history: createWebHistory(process.env.BASE_URL),
  <%_ } else { _%>
  history: createWebHashHistory(),
  <%_ } _%>
  routes
})

export default router


code:
---
extend: '@vue/cli-service/generator/template/src/App.vue'
replace:
  - !!js/regexp /<template>[^]*?<\/template>/
  - !!js/regexp /\n<script>[^]*?<\/script>\n/
  - !!js/regexp /  margin-top[^]*?<\/style>/
---

<%# REPLACE %>
<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </nav>
    <router-view/>
  </div>
</template>
<%# END_REPLACE %>

<%# REPLACE %>
<%# END_REPLACE %>

<%# REPLACE %>
}

<%_ if (rootOptions.cssPreprocessor !== 'stylus') { _%>
  <%_ if (!rootOptions.cssPreprocessor) { _%>
nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
  <%_ } else { _%>
nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
  <%_ } _%>
<%_ } else { _%>
nav
  padding 30px
  a
    font-weight bold
    color #2c3e50
    &.router-link-exact-active
      color #42b983
<%_ } _%>
</style>
<%# END_REPLACE %>


code:
import Vue from 'vue'
<%_ if (hasTypeScript) { _%>
import VueRouter, { RouteConfig } from 'vue-router'
<%_ } else { _%>
import VueRouter from 'vue-router'
<%_ } _%>
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

<%_ if (hasTypeScript) { _%>
const routes: Array<RouteConfig> = [
<%_ } else { _%>
const routes = [
<%_ } _%>
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    <%_ if (doesCompile) { _%>
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
    <%_ } else { _%>
    component: function () {
      return import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
    }
    <%_ } _%>
  }
]

const router = new VueRouter({
  <%_ if (historyMode) { _%>
  mode: 'history',
  base: process.env.BASE_URL,
  <%_ } _%>
  routes
})

export default router


code:
<template>

This is an about page

</template>


code:
<template>

    <%_ if (!rootOptions.bare) { _%>
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <%_ } else { _%>

Welcome to Your Vue.js App

    <%_ } _%>

</template>
<%_ if (!rootOptions.bare) { _%>

<%_ } _%>


code: module.exports = (api, options = {}) => {}


@vue/cli-plugin-router

description: router plugin for vue-cli

keywords: vue cli router


code:
// these prompts are used if the plugin is late-installed into an existing
// project and invoked by `vue invoke`.

const { chalk } = require('@vue/cli-shared-utils')

module.exports = [
  {
    name: 'historyMode',
    type: 'confirm',
    message: `Use history mode for router? ${chalk.yellow(`(Requires proper server setup for index fallback in production)`)}`,
    description: `By using the HTML5 History API, the URLs don't need the '#' character anymore.`
  }
]


code:
# @vue/cli-plugin-vuex

> vuex plugin for vue-cli

## Installing in an Already Created Project

```bash
vue add vuex
```


code:
module.exports = (api, options = {}, rootOptions = {}) => {
  api.injectImports(api.entryFile, `import store from './store'`)

  if (rootOptions.vueVersion === '3') {
    api.transformScript(api.entryFile, require('./injectUseStore'))
    api.extendPackage({
      dependencies: {
        vuex: '^4.0.0'
      }
    })
    api.render('./template-vue3', {})
  } else {
    api.injectRootOptions(api.entryFile, `store`)

    api.extendPackage({
      dependencies: {
        vuex: '^3.6.2'
      }
    })

    api.render('./template', {})
  }

  if (api.invoking && api.hasPlugin('typescript')) {
    /* eslint-disable-next-line node/no-extraneous-require */
    const convertFiles = require('@vue/cli-plugin-typescript/generator/convert')
    convertFiles(api)
  }
}


code:
module.exports = (file, api) => {
  const j = api.jscodeshift
  const root = j(file.source)

  const appRoots = root.find(j.CallExpression, (node) => {
    if (j.Identifier.check(node.callee) && node.callee.name === 'createApp') {
      return true
    }

    if (
      j.MemberExpression.check(node.callee) &&
      j.Identifier.check(node.callee.object) &&
      node.callee.object.name === 'Vue' &&
      j.Identifier.check(node.callee.property) &&
      node.callee.property.name === 'createApp'
    ) {
      return true
    }
  })

  appRoots.replaceWith(({ node: createAppCall }) => {
    return j.callExpression(
      j.memberExpression(createAppCall, j.identifier('use')),
      [j.identifier('store')]
    )
  })

  return root.toSource()
}


code:
import { createStore } from 'vuex'

export default createStore({
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})


code:
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})


@vue/cli-plugin-vuex

description: Vuex plugin for vue-cli

keywords: vue cli vuex


code:
# @vue/cli-service

> service for vue-cli

[Full Docs](https://cli.vuejs.org/)


code:
#!/usr/bin/env node

const { semver, error } = require('@vue/cli-shared-utils')
const requiredVersion = require('../package.json').engines.node

if (!semver.satisfies(process.version, requiredVersion, { includePrerelease: true })) {
  error(
    `You are using Node ${process.version}, but vue-cli-service ` +
    `requires Node ${requiredVersion}.\nPlease upgrade your Node version.`
  )
  process.exit(1)
}

const Service = require('../lib/Service')
const service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd())

const rawArgv = process.argv.slice(2)
const args = require('minimist')(rawArgv, {
  boolean: [
    // build
    // FIXME: --no-module, --no-unsafe-inline, no-clean, etc.
    'modern',
    'report',
    'report-json',
    'inline-vue',
    'watch',
    // serve
    'open',
    'copy',
    'https',
    // inspect
    'verbose'
  ]
})
const command = args._[0]

service.run(command, args, rawArgv).catch(err => {
  error(err)
  process.exit(1)
})


code:
module.exports = (api, options) => {
  api.render('./template', {
    doesCompile: api.hasPlugin('babel') || api.hasPlugin('typescript'),
    useBabel: api.hasPlugin('babel')
  })

  if (options.vueVersion === '3') {
    api.extendPackage({
      dependencies: {
        'vue': '^3.2.13'
      }
    })
  } else {
    api.extendPackage({
      dependencies: {
        'vue': '^2.6.14'
      },
      devDependencies: {
        'vue-template-compiler': '^2.6.14'
      }
    })
  }

  api.extendPackage({
    scripts: {
      'serve': 'vue-cli-service serve',
      'build': 'vue-cli-service build'
    },
    browserslist: [
      '> 1%',
      'last 2 versions',
      'not dead',
      ...(options.vueVersion === '3' ? ['not ie 11'] : [])
    ]
  })

  if (options.cssPreprocessor) {
    const deps = {
      sass: {
        sass: '^1.32.7',
        'sass-loader': '^12.0.0'
      },
      'dart-sass': {
        sass: '^1.32.7',
        'sass-loader': '^12.0.0'
      },
      less: {
        'less': '^4.0.0',
        'less-loader': '^8.0.0'
      },
      stylus: {
        'stylus': '^0.55.0',
        'stylus-loader': '^6.1.0'
      }
    }

    api.extendPackage({
      devDependencies: deps[options.cssPreprocessor]
    })
  }

  // for v3 compatibility
  if (options.router && !api.hasPlugin('router')) {
    require('./router')(api, options, options)
  }

  // for v3 compatibility
  if (options.vuex && !api.hasPlugin('vuex')) {
    require('./vuex')(api, options, options)
  }

  // additional tooling configurations
  if (options.configs) {
    api.extendPackage(options.configs)
  }

  // Delete jsconfig.json when typescript
  if (api.hasPlugin('typescript')) {
    api.render((files) => delete files['jsconfig.json'])
  }
}


code:
module.exports = (api, options) => {
  require('@vue/cli-plugin-router/generator')(api, {
    historyMode: options.routerHistoryMode
  })
}


code:
.DS_Store
node_modules
/dist
<%_ if (rootOptions.plugins && rootOptions.plugins['@vue/cli-plugin-e2e-nightwatch']) { _%>

/tests/e2e/reports/
selenium-debug.log
chromedriver.log
geckodriver.log
<%_ } _%>
<%_ if (rootOptions.plugins && rootOptions.plugins['@vue/cli-plugin-e2e-cypress']) { _%>

/tests/e2e/videos/
/tests/e2e/screenshots/
<%_ } _%>

<%_ if (rootOptions.plugins && rootOptions.plugins['@vue/cli-plugin-e2e-webdriverio']) { _%>

/tests/e2e/logs/
<%_ } _%>

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*

# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?


target: <%- options.useBabel ? 'esnext' : 'es5' %>

module: esnext

moduleResolution: node

lib: esnext dom dom.iterable scripthost


code:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%%= BASE_URL %%>favicon.ico">
    <title><%%= htmlWebpackPlugin.options.title %%></title>

      We're sorry but <%%= htmlWebpackPlugin.options.title %%> doesn't work properly without JavaScript enabled. Please enable it to continue.


code:
<template>
<%_ if (rootOptions.vueVersion === '3') { _%>

  <%_ if (!rootOptions.bare) { _%>
  <HelloWorld msg="Welcome to Your Vue.js App"/>
  <%_ } else { _%>

Welcome to Your Vue.js App

  <%_ } _%>
<%_ } else { _%>

    <%_ if (!rootOptions.bare) { _%>
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <%_ } else { _%>

Welcome to Your Vue.js App

    <%_ } _%>

<%_ } _%>
</template>
<%_ if (!rootOptions.bare) { _%>

<%_ if (rootOptions.cssPreprocessor !== 'stylus') { _%>

<%_ } else { _%>

<%_ } _%>
<%_ } _%>


code:
<%_ if (!rootOptions.bare) { _%>
<template>

{{ msg }}

      For a guide and recipes on how to configure / customize this project,

      check out the
      vue-cli documentation.

Installed CLI Plugins

      <%_ for (plugin of plugins) { _%>

<a href="<%- plugin.link %>" target="_blank" rel="noopener"><%- plugin.name %>

      <%_ } _%>

Essential Links

Core Docs

Forum

Community Chat

Twitter

News

Ecosystem

vue-router

vuex

vue-devtools

vue-loader

awesome-vue

</template>

<%_ if (rootOptions.cssPreprocessor !== 'stylus') { _%>

<%_ } else { _%>

<%_ } _%>
<%_ } _%>


code:
<%_ if (rootOptions.vueVersion === '3') { _%>
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
<%_ } else { _%>
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  <%_ if (doesCompile) { _%>
  render: h => h(App),
  <%_ } else { _%>
  render: function (h) { return h(App) },
  <%_ } _%>
}).$mount('#app')
<%_ } _%>


code:
module.exports = api => {
  require('@vue/cli-plugin-vuex/generator')(api)
}


code:
const path = require('path')
const hash = require('hash-sum')
const { semver, matchesPluginId } = require('@vue/cli-shared-utils')

// Note: if a plugin-registered command needs to run in a specific default mode,
// the plugin needs to expose it via `module.exports.defaultModes` in the form
// of { [commandName]: mode }. This is because the command mode needs to be
// known and applied before loading user options / applying plugins.

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
  }

  get version () {
    return require('../package.json').version
  }

  assertVersion (range) {
    if (typeof range === 'number') {
      if (!Number.isInteger(range)) {
        throw new Error('Expected string or integer value.')
      }
      range = `^${range}.0.0-0`
    }
    if (typeof range !== 'string') {
      throw new Error('Expected string or integer value.')
    }

    if (semver.satisfies(this.version, range, { includePrerelease: true })) return

    throw new Error(
      `Require @vue/cli-service "${range}", but was loaded with "${this.version}".`
    )
  }

  /**
   * Current working directory.
   */
  getCwd () {
    return this.service.context
  }

  /**
   * 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-|@scope/vue)-cli-plugin- prefix
   * @return {boolean}
   */
  hasPlugin (id) {
    return this.service.plugins.some(p => matchesPluginId(id, p.id))
  }

  /**
   * 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
      opts = null
    }
    this.service.commands[name] = { fn, opts: opts || {} }
  }

  /**
   * Register 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)
  }

  /**
   * Register
   * - 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`
   * instance 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.
   *
   * @param {ChainableWebpackConfig} [chainableConfig]
   * @return {object} Raw webpack config.
   */
  resolveWebpackConfig (chainableConfig) {
    return this.service.resolveWebpackConfig(chainableConfig)
  }

  /**
   * 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()
  }

  /**
   * Generate a cache identifier from a number of variables
   */
  genCacheConfig (id, partialIdentifier, configFiles = []) {
    const fs = require('fs')
    const cacheDirectory = this.resolve(`node_modules/.cache/${id}`)

    // replace \r\n to \n generate consistent hash
    const fmtFunc = conf => {
      if (typeof conf === 'function') {
        return conf.toString().replace(/\r\n?/g, '\n')
      }
      return conf
    }

    const variables = {
      partialIdentifier,
      'cli-service': require('../package.json').version,
      env: process.env.NODE_ENV,
      test: !!process.env.VUE_CLI_TEST,
      config: [
        fmtFunc(this.service.projectOptions.chainWebpack),
        fmtFunc(this.service.projectOptions.configureWebpack)
      ]
    }

    try {
      variables['cache-loader'] = require('cache-loader/package.json').version
    } catch (e) {
      // cache-loader is only intended to be used for webpack 4
    }

    if (!Array.isArray(configFiles)) {
      configFiles = [configFiles]
    }
    configFiles = configFiles.concat([
      'package-lock.json',
      'yarn.lock',
      'pnpm-lock.yaml'
    ])

    const readConfig = file => {
      const absolutePath = this.resolve(file)
      if (!fs.existsSync(absolutePath)) {
        return
      }

      if (absolutePath.endsWith('.js')) {
        // should evaluate config scripts to reflect environment variable changes
        try {
          return JSON.stringify(require(absolutePath))
        } catch (e) {
          return fs.readFileSync(absolutePath, 'utf-8')
        }
      } else {
        return fs.readFileSync(absolutePath, 'utf-8')
      }
    }

    variables.configFiles = configFiles.map(file => {
      const content = readConfig(file)
      return content && content.replace(/\r\n?/g, '\n')
    })

    const cacheIdentifier = hash(variables)
    return { cacheDirectory, cacheIdentifier }
  }
}

module.exports = PluginAPI


code:
const path = require('path')
const debug = require('debug')
const { merge } = require('webpack-merge')
const Config = require('webpack-chain')
const PluginAPI = require('./PluginAPI')
const dotenv = require('dotenv')
const dotenvExpand = require('dotenv-expand')
const defaultsDeep = require('lodash.defaultsdeep')
const { warn, error, isPlugin, resolvePluginId, loadModule, resolvePkg, resolveModule, sortPlugins } = require('@vue/cli-shared-utils')

const { defaults } = require('./options')
const loadFileConfig = require('./util/loadFileConfig')
const resolveUserConfig = require('./util/resolveUserConfig')

// Seems we can't use `instanceof Promise` here (would fail the tests)
const isPromise = p => p && typeof p.then === 'function'
module.exports = class Service {
  constructor (context, { plugins, pkg, inlineOptions, useBuiltIn } = {}) {
    process.VUE_CLI_SERVICE = this
    this.initialized = false
    this.context = context
    this.inlineOptions = inlineOptions
    this.webpackChainFns = []
    this.webpackRawConfigFns = []
    this.devServerConfigFns = []
    this.commands = {}
    // Folder containing the target package.json for plugins
    this.pkgContext = context
    // package.json containing the plugins
    this.pkg = this.resolvePkg(pkg)
    // If there are inline plugins, they will be used instead of those
    // found in package.json.
    // When useBuiltIn === false, built-in plugins are disabled. This is mostly
    // for testing.
    this.plugins = this.resolvePlugins(plugins, useBuiltIn)
    // pluginsToSkip will be populated during run()
    this.pluginsToSkip = new Set()
    // resolve the default mode to use for each command
    // this is provided by plugins as module.exports.defaultModes
    // so we can get the information without actually applying the plugin.
    this.modes = this.plugins.reduce((modes, { apply: { defaultModes } }) => {
      return Object.assign(modes, defaultModes)
    }, {})
  }

  resolvePkg (inlinePkg, context = this.context) {
    if (inlinePkg) {
      return inlinePkg
    }
    const pkg = resolvePkg(context)
    if (pkg.vuePlugins && pkg.vuePlugins.resolveFrom) {
      this.pkgContext = path.resolve(context, pkg.vuePlugins.resolveFrom)
      return this.resolvePkg(null, this.pkgContext)
    }
    return pkg
  }

  init (mode = process.env.VUE_CLI_MODE) {
    if (this.initialized) {
      return
    }
    this.initialized = true
    this.mode = mode

    // load mode .env
    if (mode) {
      this.loadEnv(mode)
    }
    // load base .env
    this.loadEnv()

    // load user config
    const userOptions = this.loadUserOptions()
    const loadedCallback = (loadedUserOptions) => {
      this.projectOptions = defaultsDeep(loadedUserOptions, defaults())

      debug('vue:project-config')(this.projectOptions)

      // apply plugins.
      this.plugins.forEach(({ id, apply }) => {
        if (this.pluginsToSkip.has(id)) return
        apply(new PluginAPI(id, this), this.projectOptions)
      })

      // apply webpack configs from project config file
      if (this.projectOptions.chainWebpack) {
        this.webpackChainFns.push(this.projectOptions.chainWebpack)
      }
      if (this.projectOptions.configureWebpack) {
        this.webpackRawConfigFns.push(this.projectOptions.configureWebpack)
      }
    }

    if (isPromise(userOptions)) {
      return userOptions.then(loadedCallback)
    } else {
      return loadedCallback(userOptions)
    }
  }

  loadEnv (mode) {
    const logger = debug('vue:env')
    const basePath = path.resolve(this.context, `.env${mode ? `.${mode}` : ``}`)
    const localPath = `${basePath}.local`

    const load = envPath => {
      try {
        const env = dotenv.config({ path: envPath, debug: process.env.DEBUG })
        dotenvExpand(env)
        logger(envPath, env)
      } catch (err) {
        // only ignore error if file is not found
        if (err.toString().indexOf('ENOENT') < 0) {
          error(err)
        }
      }
    }

    load(localPath)
    load(basePath)

    // by default, NODE_ENV and BABEL_ENV are set to "development" unless mode
    // is production or test. However the value in .env files will take higher
    // priority.
    if (mode) {
      // always set NODE_ENV during tests
      // as that is necessary for tests to not be affected by each other
      const shouldForceDefaultEnv = (
        process.env.VUE_CLI_TEST &&
        !process.env.VUE_CLI_TEST_TESTING_ENV
      )
      const defaultNodeEnv = (mode === 'production' || mode === 'test')
        ? mode
        : 'development'
      if (shouldForceDefaultEnv || process.env.NODE_ENV == null) {
        process.env.NODE_ENV = defaultNodeEnv
      }
      if (shouldForceDefaultEnv || process.env.BABEL_ENV == null) {
        process.env.BABEL_ENV = defaultNodeEnv
      }
    }
  }

  setPluginsToSkip (args, rawArgv) {
    let skipPlugins = args['skip-plugins']
    const pluginsToSkip = new Set()
    if (skipPlugins) {
      // When only one appearence, convert to array to prevent duplicate code
      if (!Array.isArray(skipPlugins)) {
        skipPlugins = Array.from([skipPlugins])
      }
      // Iter over all --skip-plugins appearences
      for (const value of skipPlugins.values()) {
        for (const plugin of value.split(',').map(id => resolvePluginId(id))) {
          pluginsToSkip.add(plugin)
        }
      }
    }
    this.pluginsToSkip = pluginsToSkip

    delete args['skip-plugins']
    // Delete all --skip-plugin appearences
    let index
    while ((index = rawArgv.indexOf('--skip-plugins')) > -1) {
      rawArgv.splice(index, 2) // Remove the argument and its value
    }
  }

  resolvePlugins (inlinePlugins, useBuiltIn) {
    const idToPlugin = (id, absolutePath) => ({
      id: id.replace(/^.\//, 'built-in:'),
      apply: require(absolutePath || id)
    })

    let plugins

    const builtInPlugins = [
      './commands/serve',
      './commands/build',
      './commands/inspect',
      './commands/help',
      // config plugins are order sensitive
      './config/base',
      './config/assets',
      './config/css',
      './config/prod',
      './config/app'
    ].map((id) => idToPlugin(id))

    if (inlinePlugins) {
      plugins = useBuiltIn !== false
        ? builtInPlugins.concat(inlinePlugins)
        : inlinePlugins
    } else {
      const projectPlugins = Object.keys(this.pkg.devDependencies || {})
        .concat(Object.keys(this.pkg.dependencies || {}))
        .filter(isPlugin)
        .map(id => {
          if (
            this.pkg.optionalDependencies &&
            id in this.pkg.optionalDependencies
          ) {
            let apply = loadModule(id, this.pkgContext)
            if (!apply) {
              warn(`Optional dependency ${id} is not installed.`)
              apply = () => {}
            }

            return { id, apply }
          } else {
            return idToPlugin(id, resolveModule(id, this.pkgContext))
          }
        })

      plugins = builtInPlugins.concat(projectPlugins)
    }

    // Local plugins
    if (this.pkg.vuePlugins && this.pkg.vuePlugins.service) {
      const files = this.pkg.vuePlugins.service
      if (!Array.isArray(files)) {
        throw new Error(`Invalid type for option 'vuePlugins.service', expected 'array' but got ${typeof files}.`)
      }
      plugins = plugins.concat(files.map(file => ({
        id: `local:${file}`,
        apply: loadModule(`./${file}`, this.pkgContext)
      })))
    }
    debug('vue:plugins')(plugins)

    const orderedPlugins = sortPlugins(plugins)
    debug('vue:plugins-ordered')(orderedPlugins)

    return orderedPlugins
  }

  async run (name, args = {}, rawArgv = []) {
    // resolve mode
    // prioritize inline --mode
    // fallback to resolved default modes from plugins or development if --watch is defined
    const mode = args.mode || (name === 'build' && args.watch ? 'development' : this.modes[name])

    // --skip-plugins arg may have plugins that should be skipped during init()
    this.setPluginsToSkip(args, rawArgv)

    // load env variables, load user config, apply plugins
    await this.init(mode)

    args._ = args._ || []
    let command = this.commands[name]
    if (!command && name) {
      error(`command "${name}" does not exist.`)
      process.exit(1)
    }
    if (!command || args.help || args.h) {
      command = this.commands.help
    } else {
      args._.shift() // remove command itself
      rawArgv.shift()
    }
    const { fn } = command
    return fn(args, rawArgv)
  }

  resolveChainableWebpackConfig () {
    const chainableConfig = new Config()
    // apply chains
    this.webpackChainFns.forEach(fn => fn(chainableConfig))
    return chainableConfig
  }

  resolveWebpackConfig (chainableConfig = this.resolveChainableWebpackConfig()) {
    if (!this.initialized) {
      throw new Error('Service must call init() before calling resolveWebpackConfig().')
    }
    // get raw config
    let config = chainableConfig.toConfig()
    const original = config
    // apply raw config fns
    this.webpackRawConfigFns.forEach(fn => {
      if (typeof fn === 'function') {
        // function with optional return value
        const res = fn(config)
        if (res) config = merge(config, res)
      } else if (fn) {
        // merge literal values
        config = merge(config, fn)
      }
    })

    // #2206 If config is merged by merge-webpack, it discards the __ruleNames
    // information injected by webpack-chain. Restore the info so that
    // vue inspect works properly.
    if (config !== original) {
      cloneRuleNames(
        config.module && config.module.rules,
        original.module && original.module.rules
      )
    }

    // check if the user has manually mutated output.publicPath
    const target = process.env.VUE_CLI_BUILD_TARGET
    if (
      !process.env.VUE_CLI_TEST &&
      (target && target !== 'app') &&
      config.output.publicPath !== this.projectOptions.publicPath
    ) {
      throw new Error(
        `Do not modify webpack output.publicPath directly. ` +
        `Use the "publicPath" option in vue.config.js instead.`
      )
    }

    if (
      !process.env.VUE_CLI_ENTRY_FILES &&
      typeof config.entry !== 'function'
    ) {
      let entryFiles
      if (typeof config.entry === 'string') {
        entryFiles = [config.entry]
      } else if (Array.isArray(config.entry)) {
        entryFiles = config.entry
      } else {
        entryFiles = Object.values(config.entry || []).reduce((allEntries, curr) => {
          return allEntries.concat(curr)
        }, [])
      }

      entryFiles = entryFiles.map(file => path.resolve(this.context, file))
      process.env.VUE_CLI_ENTRY_FILES = JSON.stringify(entryFiles)
    }

    return config
  }

  // Note: we intentionally make this function synchronous by default
  // because eslint-import-resolver-webpack does not support async webpack configs.
  loadUserOptions () {
    const { fileConfig, fileConfigPath } = loadFileConfig(this.context)

    if (isPromise(fileConfig)) {
      return fileConfig
        .then(mod => mod.default)
        .then(loadedConfig => resolveUserConfig({
          inlineOptions: this.inlineOptions,
          pkgConfig: this.pkg.vue,
          fileConfig: loadedConfig,
          fileConfigPath
        }))
    }

    return resolveUserConfig({
      inlineOptions: this.inlineOptions,
      pkgConfig: this.pkg.vue,
      fileConfig,
      fileConfigPath
    })
  }
}

function cloneRuleNames (to, from) {
  if (!to || !from) {
    return
  }
  from.forEach((r, i) => {
    if (to[i]) {
      Object.defineProperty(to[i], '__ruleNames', {
        value: r.__ruleNames
      })
      cloneRuleNames(to[i].oneOf, r.oneOf)
    }
  })
}

/** @type {import('../types/index').defineConfig} */
module.exports.defineConfig = (config) => config


code:
<!DOCTYPE html>
<meta charset="utf-8">
<title><%- htmlWebpackPlugin.options.libName %> demo</title>
<script src="./<%- htmlWebpackPlugin.options.assetsFileName %>.umd.js"></script>
<% if (htmlWebpackPlugin.options.cssExtract) { %>
<link rel="stylesheet" href="./<%- htmlWebpackPlugin.options.assetsFileName %>.css">
<% } %>

<script>
console.log(<%- htmlWebpackPlugin.options.libName %>)
</script>


code:
<!DOCTYPE html>
<meta charset="utf-8">
<title><%- htmlWebpackPlugin.options.libName %> demo</title>
<script src="//unpkg.com/vue@<%- htmlWebpackPlugin.options.vueMajor %>"></script>
<script src="./<%- htmlWebpackPlugin.options.assetsFileName %>.umd.js"></script>
<% if (htmlWebpackPlugin.options.cssExtract) { %>
<link rel="stylesheet" href="./<%- htmlWebpackPlugin.options.assetsFileName %>.css">
<% } %>

<div id="app">
  <demo></demo>
</div>

<script>
<% if (htmlWebpackPlugin.options.vueMajor === 3) { %>
Vue.createApp({
  components: {
    demo: <%- htmlWebpackPlugin.options.libName %>
  }
}).mount('#app')
<% } else { %>
new Vue({
  components: {
    demo: <%- htmlWebpackPlugin.options.libName %>
  }
}).$mount('#app')
<% } %>
</script>


code:
<!DOCTYPE html>
<meta charset="utf-8">
<title><%- htmlWebpackPlugin.options.libName %> demo</title>
<script src="https://unpkg.com/vue@<%- htmlWebpackPlugin.options.vueMajor %>"></script>
<script src="./<%- htmlWebpackPlugin.options.libName %>.js"></script>

<% for (const comp of htmlWebpackPlugin.options.components) { %>
<<%= comp %>></<%= comp %>>
<% } %>


code:
import './setPublicPath'
export * from '~entry'


code:
import './setPublicPath'
import mod from '~entry'
export default mod
export * from '~entry'


code:
import './setPublicPath'
import Vue from 'vue'
import wrap from '@vue/web-component-wrapper'

// runtime shared by every component chunk
import 'css-loader/dist/runtime/api.js'
import 'vue-style-loader/lib/addStylesShadow'
import 'vue-loader/lib/runtime/componentNormalizer'

window.customElements.define('build-wc-async-app', wrap(Vue, () => import('~root/src/App.vue?shadow')))

window.customElements.define('build-wc-async-hello-world', wrap(Vue, () => import('~root/src/components/HelloWorld.vue?shadow')))


code:
module.exports = function formatStats (stats, dir, api) {
  const fs = require('fs')
  const path = require('path')
  const zlib = require('zlib')
  const ui = require('cliui')({ width: process.stdout.columns || 80 })
  const { chalk } = require('@vue/cli-shared-utils')

  const json = stats.toJson({
    hash: false,
    modules: false,
    chunks: false
  })

  let assets = json.assets
    ? json.assets
    : json.children.reduce((acc, child) => acc.concat(child.assets), [])

  const seenNames = new Map()
  const isJS = val => /\.js$/.test(val)
  const isCSS = val => /\.css$/.test(val)
  const isMinJS = val => /\.min\.js$/.test(val)
  assets = assets
    .map(a => {
      a.name = a.name.split('?')[0]
      return a
    })
    .filter(a => {
      if (seenNames.has(a.name)) {
        return false
      }
      seenNames.set(a.name, true)
      return isJS(a.name) || isCSS(a.name)
    })
    .sort((a, b) => {
      if (isJS(a.name) && isCSS(b.name)) return -1
      if (isCSS(a.name) && isJS(b.name)) return 1
      if (isMinJS(a.name) && !isMinJS(b.name)) return -1
      if (!isMinJS(a.name) && isMinJS(b.name)) return 1
      return b.size - a.size
    })

  function formatSize (size) {
    return (size / 1024).toFixed(2) + ' KiB'
  }

  function getGzippedSize (asset) {
    const filepath = api.resolve(path.join(dir, asset.name))
    const buffer = fs.readFileSync(filepath)
    return formatSize(zlib.gzipSync(buffer).length)
  }

  function makeRow (a, b, c) {
    return `  ${a}\t    ${b}\t ${c}`
  }

  ui.div(
    makeRow(
      chalk.cyan.bold(`File`),
      chalk.cyan.bold(`Size`),
      chalk.cyan.bold(`Gzipped`)
    ) + `\n\n` +
    assets.map(asset => makeRow(
      /js$/.test(asset.name)
        ? chalk.green(path.join(dir, asset.name))
        : chalk.blue(path.join(dir, asset.name)),
      formatSize(asset.size),
      getGzippedSize(asset)
    )).join(`\n`)
  )

  const time = stats.endTime - stats.startTime
  const now = new Date().toISOString()
  const hash = stats.hash
  const info = `Build at: ${chalk.white(now)} - Hash: ${chalk.white(hash)} - Time: ${chalk.white(time)}ms`

  return `${ui.toString()}\n\n  ${chalk.gray(`Images and other types of assets omitted.`)}\n  ${info}\n`
}