index.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. const defaults = {
  2. clean: true,
  3. target: 'app',
  4. formats: 'commonjs,umd,umd-min',
  5. 'unsafe-inline': true
  6. }
  7. const buildModes = {
  8. lib: 'library',
  9. wc: 'web component',
  10. 'wc-async': 'web component (async)'
  11. }
  12. const modifyConfig = (config, fn) => {
  13. if (Array.isArray(config)) {
  14. config.forEach(c => fn(c))
  15. } else {
  16. fn(config)
  17. }
  18. }
  19. module.exports = (api, options) => {
  20. api.registerCommand('build', {
  21. description: 'build for production',
  22. usage: 'vue-cli-service build [options] [entry|pattern]',
  23. options: {
  24. '--mode': `specify env mode (default: production)`,
  25. '--dest': `specify output directory (default: ${options.outputDir})`,
  26. '--modern': `build app targeting modern browsers with auto fallback`,
  27. '--no-unsafe-inline': `build app without introducing inline scripts`,
  28. '--target': `app | lib | wc | wc-async (default: ${defaults.target})`,
  29. '--inline-vue': 'include the Vue module in the final bundle of library or web component target',
  30. '--formats': `list of output formats for library builds (default: ${defaults.formats})`,
  31. '--name': `name for lib or web-component mode (default: "name" in package.json or entry filename)`,
  32. '--filename': `file name for output, only usable for 'lib' target (default: value of --name)`,
  33. '--no-clean': `do not remove the dist directory before building the project`,
  34. '--report': `generate report.html to help analyze bundle content`,
  35. '--report-json': 'generate report.json to help analyze bundle content',
  36. '--skip-plugins': `comma-separated list of plugin names to skip for this run`,
  37. '--watch': `watch for changes`
  38. }
  39. }, async (args, rawArgs) => {
  40. for (const key in defaults) {
  41. if (args[key] == null) {
  42. args[key] = defaults[key]
  43. }
  44. }
  45. args.entry = args.entry || args._[0]
  46. if (args.target !== 'app') {
  47. args.entry = args.entry || 'src/App.vue'
  48. }
  49. process.env.VUE_CLI_BUILD_TARGET = args.target
  50. if (args.modern && args.target === 'app') {
  51. process.env.VUE_CLI_MODERN_MODE = true
  52. if (!process.env.VUE_CLI_MODERN_BUILD) {
  53. // main-process for legacy build
  54. await build(Object.assign({}, args, {
  55. modernBuild: false,
  56. keepAlive: true
  57. }), api, options)
  58. // spawn sub-process of self for modern build
  59. const { execa } = require('@vue/cli-shared-utils')
  60. const cliBin = require('path').resolve(__dirname, '../../../bin/vue-cli-service.js')
  61. await execa(cliBin, ['build', ...rawArgs], {
  62. stdio: 'inherit',
  63. env: {
  64. VUE_CLI_MODERN_BUILD: true
  65. }
  66. })
  67. } else {
  68. // sub-process for modern build
  69. await build(Object.assign({}, args, {
  70. modernBuild: true,
  71. clean: false
  72. }), api, options)
  73. }
  74. delete process.env.VUE_CLI_MODERN_MODE
  75. } else {
  76. if (args.modern) {
  77. const { warn } = require('@vue/cli-shared-utils')
  78. warn(
  79. `Modern mode only works with default target (app). ` +
  80. `For libraries or web components, use the browserslist ` +
  81. `config to specify target browsers.`
  82. )
  83. }
  84. await build(args, api, options)
  85. }
  86. delete process.env.VUE_CLI_BUILD_TARGET
  87. })
  88. }
  89. async function build (args, api, options) {
  90. const fs = require('fs-extra')
  91. const path = require('path')
  92. const chalk = require('chalk')
  93. const webpack = require('webpack')
  94. const formatStats = require('./formatStats')
  95. const validateWebpackConfig = require('../../util/validateWebpackConfig')
  96. const {
  97. log,
  98. done,
  99. info,
  100. logWithSpinner,
  101. stopSpinner
  102. } = require('@vue/cli-shared-utils')
  103. log()
  104. const mode = api.service.mode
  105. if (args.target === 'app') {
  106. const bundleTag = args.modern
  107. ? args.modernBuild
  108. ? `modern bundle `
  109. : `legacy bundle `
  110. : ``
  111. logWithSpinner(`Building ${bundleTag}for ${mode}...`)
  112. } else {
  113. const buildMode = buildModes[args.target]
  114. if (buildMode) {
  115. const additionalParams = buildMode === 'library' ? ` (${args.formats})` : ``
  116. logWithSpinner(`Building for ${mode} as ${buildMode}${additionalParams}...`)
  117. } else {
  118. throw new Error(`Unknown build target: ${args.target}`)
  119. }
  120. }
  121. if (args.dest) {
  122. // Override outputDir before resolving webpack config as config relies on it (#2327)
  123. options.outputDir = args.dest
  124. }
  125. const targetDir = api.resolve(options.outputDir)
  126. const isLegacyBuild = args.target === 'app' && args.modern && !args.modernBuild
  127. // resolve raw webpack config
  128. let webpackConfig
  129. if (args.target === 'lib') {
  130. webpackConfig = require('./resolveLibConfig')(api, args, options)
  131. } else if (
  132. args.target === 'wc' ||
  133. args.target === 'wc-async'
  134. ) {
  135. webpackConfig = require('./resolveWcConfig')(api, args, options)
  136. } else {
  137. webpackConfig = require('./resolveAppConfig')(api, args, options)
  138. }
  139. // check for common config errors
  140. validateWebpackConfig(webpackConfig, api, options, args.target)
  141. if (args.watch) {
  142. modifyConfig(webpackConfig, config => {
  143. config.watch = true
  144. })
  145. }
  146. // Expose advanced stats
  147. if (args.dashboard) {
  148. const DashboardPlugin = require('../../webpack/DashboardPlugin')
  149. modifyConfig(webpackConfig, config => {
  150. config.plugins.push(new DashboardPlugin({
  151. type: 'build',
  152. modernBuild: args.modernBuild,
  153. keepAlive: args.keepAlive
  154. }))
  155. })
  156. }
  157. if (args.report || args['report-json']) {
  158. const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
  159. modifyConfig(webpackConfig, config => {
  160. const bundleName = args.target !== 'app'
  161. ? config.output.filename.replace(/\.js$/, '-')
  162. : isLegacyBuild ? 'legacy-' : ''
  163. config.plugins.push(new BundleAnalyzerPlugin({
  164. logLevel: 'warn',
  165. openAnalyzer: false,
  166. analyzerMode: args.report ? 'static' : 'disabled',
  167. reportFilename: `${bundleName}report.html`,
  168. statsFilename: `${bundleName}report.json`,
  169. generateStatsFile: !!args['report-json']
  170. }))
  171. })
  172. }
  173. if (args.clean) {
  174. await fs.remove(targetDir)
  175. }
  176. return new Promise((resolve, reject) => {
  177. webpack(webpackConfig, (err, stats) => {
  178. stopSpinner(false)
  179. if (err) {
  180. return reject(err)
  181. }
  182. if (stats.hasErrors()) {
  183. return reject(`Build failed with errors.`)
  184. }
  185. if (!args.silent) {
  186. const targetDirShort = path.relative(
  187. api.service.context,
  188. targetDir
  189. )
  190. log(formatStats(stats, targetDirShort, api))
  191. if (args.target === 'app' && !isLegacyBuild) {
  192. if (!args.watch) {
  193. done(`Build complete. The ${chalk.cyan(targetDirShort)} directory is ready to be deployed.`)
  194. info(`Check out deployment instructions at ${chalk.cyan(`https://cli.vuejs.org/guide/deployment.html`)}\n`)
  195. } else {
  196. done(`Build complete. Watching for changes...`)
  197. }
  198. }
  199. }
  200. // test-only signal
  201. if (process.env.VUE_CLI_TEST) {
  202. console.log('Build complete.')
  203. }
  204. resolve()
  205. })
  206. })
  207. }
  208. module.exports.defaultModes = {
  209. build: 'production'
  210. }