index.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. '--stdin': `close when stdin ends`
  39. }
  40. }, async (args, rawArgs) => {
  41. for (const key in defaults) {
  42. if (args[key] == null) {
  43. args[key] = defaults[key]
  44. }
  45. }
  46. args.entry = args.entry || args._[0]
  47. if (args.target !== 'app') {
  48. args.entry = args.entry || 'src/App.vue'
  49. }
  50. process.env.VUE_CLI_BUILD_TARGET = args.target
  51. if (args.modern && args.target === 'app') {
  52. process.env.VUE_CLI_MODERN_MODE = true
  53. if (!process.env.VUE_CLI_MODERN_BUILD) {
  54. // main-process for legacy build
  55. await build(Object.assign({}, args, {
  56. modernBuild: false,
  57. keepAlive: true
  58. }), api, options)
  59. // spawn sub-process of self for modern build
  60. const { execa } = require('@vue/cli-shared-utils')
  61. const cliBin = require('path').resolve(__dirname, '../../../bin/vue-cli-service.js')
  62. await execa('node', [cliBin, 'build', ...rawArgs], {
  63. stdio: 'inherit',
  64. env: {
  65. VUE_CLI_MODERN_BUILD: true
  66. }
  67. })
  68. } else {
  69. // sub-process for modern build
  70. await build(Object.assign({}, args, {
  71. modernBuild: true,
  72. clean: false
  73. }), api, options)
  74. }
  75. delete process.env.VUE_CLI_MODERN_MODE
  76. } else {
  77. if (args.modern) {
  78. const { warn } = require('@vue/cli-shared-utils')
  79. warn(
  80. `Modern mode only works with default target (app). ` +
  81. `For libraries or web components, use the browserslist ` +
  82. `config to specify target browsers.`
  83. )
  84. }
  85. await build(args, api, options)
  86. }
  87. delete process.env.VUE_CLI_BUILD_TARGET
  88. })
  89. }
  90. async function build (args, api, options) {
  91. const fs = require('fs-extra')
  92. const path = require('path')
  93. const webpack = require('webpack')
  94. const { chalk } = require('@vue/cli-shared-utils')
  95. const formatStats = require('./formatStats')
  96. const validateWebpackConfig = require('../../util/validateWebpackConfig')
  97. const {
  98. log,
  99. done,
  100. info,
  101. logWithSpinner,
  102. stopSpinner
  103. } = require('@vue/cli-shared-utils')
  104. log()
  105. const mode = api.service.mode
  106. if (args.target === 'app') {
  107. const bundleTag = args.modern
  108. ? args.modernBuild
  109. ? `modern bundle `
  110. : `legacy bundle `
  111. : ``
  112. logWithSpinner(`Building ${bundleTag}for ${mode}...`)
  113. } else {
  114. const buildMode = buildModes[args.target]
  115. if (buildMode) {
  116. const additionalParams = buildMode === 'library' ? ` (${args.formats})` : ``
  117. logWithSpinner(`Building for ${mode} as ${buildMode}${additionalParams}...`)
  118. } else {
  119. throw new Error(`Unknown build target: ${args.target}`)
  120. }
  121. }
  122. if (args.dest) {
  123. // Override outputDir before resolving webpack config as config relies on it (#2327)
  124. options.outputDir = args.dest
  125. }
  126. const targetDir = api.resolve(options.outputDir)
  127. const isLegacyBuild = args.target === 'app' && args.modern && !args.modernBuild
  128. // resolve raw webpack config
  129. let webpackConfig
  130. if (args.target === 'lib') {
  131. webpackConfig = require('./resolveLibConfig')(api, args, options)
  132. } else if (
  133. args.target === 'wc' ||
  134. args.target === 'wc-async'
  135. ) {
  136. webpackConfig = require('./resolveWcConfig')(api, args, options)
  137. } else {
  138. webpackConfig = require('./resolveAppConfig')(api, args, options)
  139. }
  140. // check for common config errors
  141. validateWebpackConfig(webpackConfig, api, options, args.target)
  142. if (args.watch) {
  143. modifyConfig(webpackConfig, config => {
  144. config.watch = true
  145. })
  146. }
  147. if (args.stdin) {
  148. process.stdin.on('end', () => {
  149. process.exit(0)
  150. })
  151. process.stdin.resume()
  152. }
  153. // Expose advanced stats
  154. if (args.dashboard) {
  155. const DashboardPlugin = require('../../webpack/DashboardPlugin')
  156. modifyConfig(webpackConfig, config => {
  157. config.plugins.push(new DashboardPlugin({
  158. type: 'build',
  159. modernBuild: args.modernBuild,
  160. keepAlive: args.keepAlive
  161. }))
  162. })
  163. }
  164. if (args.report || args['report-json']) {
  165. const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
  166. modifyConfig(webpackConfig, config => {
  167. const bundleName = args.target !== 'app'
  168. ? config.output.filename.replace(/\.js$/, '-')
  169. : isLegacyBuild ? 'legacy-' : ''
  170. config.plugins.push(new BundleAnalyzerPlugin({
  171. logLevel: 'warn',
  172. openAnalyzer: false,
  173. analyzerMode: args.report ? 'static' : 'disabled',
  174. reportFilename: `${bundleName}report.html`,
  175. statsFilename: `${bundleName}report.json`,
  176. generateStatsFile: !!args['report-json']
  177. }))
  178. })
  179. }
  180. if (args.clean) {
  181. await fs.remove(targetDir)
  182. }
  183. return new Promise((resolve, reject) => {
  184. webpack(webpackConfig, (err, stats) => {
  185. stopSpinner(false)
  186. if (err) {
  187. return reject(err)
  188. }
  189. if (stats.hasErrors()) {
  190. return reject(`Build failed with errors.`)
  191. }
  192. if (!args.silent) {
  193. const targetDirShort = path.relative(
  194. api.service.context,
  195. targetDir
  196. )
  197. log(formatStats(stats, targetDirShort, api))
  198. if (args.target === 'app' && !isLegacyBuild) {
  199. if (!args.watch) {
  200. done(`Build complete. The ${chalk.cyan(targetDirShort)} directory is ready to be deployed.`)
  201. info(`Check out deployment instructions at ${chalk.cyan(`https://cli.vuejs.org/guide/deployment.html`)}\n`)
  202. } else {
  203. done(`Build complete. Watching for changes...`)
  204. }
  205. }
  206. }
  207. // test-only signal
  208. if (process.env.VUE_CLI_TEST) {
  209. console.log('Build complete.')
  210. }
  211. resolve()
  212. })
  213. })
  214. }
  215. module.exports.defaultModes = {
  216. build: 'production'
  217. }