serve.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. const {
  2. info,
  3. hasProjectYarn,
  4. hasProjectPnpm,
  5. openBrowser,
  6. IpcMessenger
  7. } = require('@vue/cli-shared-utils')
  8. const defaults = {
  9. host: '0.0.0.0',
  10. port: 8080,
  11. https: false
  12. }
  13. module.exports = (api, options) => {
  14. api.registerCommand('serve', {
  15. description: 'start development server',
  16. usage: 'vue-cli-service serve [options] [entry]',
  17. options: {
  18. '--open': `open browser on server start`,
  19. '--copy': `copy url to clipboard on server start`,
  20. '--mode': `specify env mode (default: development)`,
  21. '--host': `specify host (default: ${defaults.host})`,
  22. '--port': `specify port (default: ${defaults.port})`,
  23. '--https': `use https (default: ${defaults.https})`,
  24. '--public': `specify the public network URL for the HMR client`
  25. }
  26. }, async function serve (args) {
  27. info('Starting development server...')
  28. // although this is primarily a dev server, it is possible that we
  29. // are running it in a mode with a production env, e.g. in E2E tests.
  30. const isInContainer = checkInContainer()
  31. const isProduction = process.env.NODE_ENV === 'production'
  32. const url = require('url')
  33. const chalk = require('chalk')
  34. const webpack = require('webpack')
  35. const WebpackDevServer = require('webpack-dev-server')
  36. const portfinder = require('portfinder')
  37. const prepareURLs = require('../util/prepareURLs')
  38. const prepareProxy = require('../util/prepareProxy')
  39. const launchEditorMiddleware = require('launch-editor-middleware')
  40. const validateWebpackConfig = require('../util/validateWebpackConfig')
  41. const isAbsoluteUrl = require('../util/isAbsoluteUrl')
  42. // resolve webpack config
  43. const webpackConfig = api.resolveWebpackConfig()
  44. // check for common config errors
  45. validateWebpackConfig(webpackConfig, api, options)
  46. // load user devServer options with higher priority than devServer
  47. // in webpck config
  48. const projectDevServerOptions = Object.assign(
  49. webpackConfig.devServer || {},
  50. options.devServer
  51. )
  52. // expose advanced stats
  53. if (args.dashboard) {
  54. const DashboardPlugin = require('../webpack/DashboardPlugin')
  55. ;(webpackConfig.plugins = webpackConfig.plugins || []).push(new DashboardPlugin({
  56. type: 'serve'
  57. }))
  58. }
  59. // entry arg
  60. const entry = args._[0]
  61. if (entry) {
  62. webpackConfig.entry = {
  63. app: api.resolve(entry)
  64. }
  65. }
  66. // resolve server options
  67. const useHttps = args.https || projectDevServerOptions.https || defaults.https
  68. const protocol = useHttps ? 'https' : 'http'
  69. const host = args.host || process.env.HOST || projectDevServerOptions.host || defaults.host
  70. portfinder.basePort = args.port || process.env.PORT || projectDevServerOptions.port || defaults.port
  71. const port = await portfinder.getPortPromise()
  72. const rawPublicUrl = args.public || projectDevServerOptions.public
  73. const publicUrl = rawPublicUrl
  74. ? /^[a-zA-Z]+:\/\//.test(rawPublicUrl)
  75. ? rawPublicUrl
  76. : `${protocol}://${rawPublicUrl}`
  77. : null
  78. const urls = prepareURLs(
  79. protocol,
  80. host,
  81. port,
  82. isAbsoluteUrl(options.publicPath) ? '/' : options.publicPath
  83. )
  84. const proxySettings = prepareProxy(
  85. projectDevServerOptions.proxy,
  86. api.resolve('public')
  87. )
  88. // inject dev & hot-reload middleware entries
  89. if (!isProduction) {
  90. const sockjsUrl = publicUrl
  91. // explicitly configured via devServer.public
  92. ? `?${publicUrl}/sockjs-node`
  93. : isInContainer
  94. // can't infer public netowrk url if inside a container...
  95. // use client-side inference (note this would break with non-root publicPath)
  96. ? ``
  97. // otherwise infer the url
  98. : `?` + url.format({
  99. protocol,
  100. port,
  101. hostname: urls.lanUrlForConfig || 'localhost',
  102. pathname: '/sockjs-node'
  103. })
  104. const devClients = [
  105. // dev server client
  106. require.resolve(`webpack-dev-server/client`) + sockjsUrl,
  107. // hmr client
  108. require.resolve(projectDevServerOptions.hotOnly
  109. ? 'webpack/hot/only-dev-server'
  110. : 'webpack/hot/dev-server')
  111. // TODO custom overlay client
  112. // `@vue/cli-overlay/dist/client`
  113. ]
  114. if (process.env.APPVEYOR) {
  115. devClients.push(`webpack/hot/poll?500`)
  116. }
  117. // inject dev/hot client
  118. addDevClientToEntry(webpackConfig, devClients)
  119. }
  120. // create compiler
  121. const compiler = webpack(webpackConfig)
  122. // create server
  123. const server = new WebpackDevServer(compiler, Object.assign({
  124. clientLogLevel: 'none',
  125. historyApiFallback: {
  126. disableDotRule: true,
  127. rewrites: genHistoryApiFallbackRewrites(options.publicPath, options.pages)
  128. },
  129. contentBase: api.resolve('public'),
  130. watchContentBase: !isProduction,
  131. hot: !isProduction,
  132. quiet: true,
  133. compress: isProduction,
  134. publicPath: options.publicPath,
  135. overlay: isProduction // TODO disable this
  136. ? false
  137. : { warnings: false, errors: true }
  138. }, projectDevServerOptions, {
  139. https: useHttps,
  140. proxy: proxySettings,
  141. before (app, server) {
  142. // launch editor support.
  143. // this works with vue-devtools & @vue/cli-overlay
  144. app.use('/__open-in-editor', launchEditorMiddleware(() => console.log(
  145. `To specify an editor, sepcify the EDITOR env variable or ` +
  146. `add "editor" field to your Vue project config.\n`
  147. )))
  148. // allow other plugins to register middlewares, e.g. PWA
  149. api.service.devServerConfigFns.forEach(fn => fn(app, server))
  150. // apply in project middlewares
  151. projectDevServerOptions.before && projectDevServerOptions.before(app, server)
  152. }
  153. }))
  154. ;['SIGINT', 'SIGTERM'].forEach(signal => {
  155. process.on(signal, () => {
  156. server.close(() => {
  157. process.exit(0)
  158. })
  159. })
  160. })
  161. // on appveyor, killing the process with SIGTERM causes execa to
  162. // throw error
  163. if (process.env.VUE_CLI_TEST) {
  164. process.stdin.on('data', data => {
  165. if (data.toString() === 'close') {
  166. console.log('got close signal!')
  167. server.close(() => {
  168. process.exit(0)
  169. })
  170. }
  171. })
  172. }
  173. return new Promise((resolve, reject) => {
  174. // log instructions & open browser on first compilation complete
  175. let isFirstCompile = true
  176. compiler.hooks.done.tap('vue-cli-service serve', stats => {
  177. if (stats.hasErrors()) {
  178. return
  179. }
  180. let copied = ''
  181. if (isFirstCompile && args.copy) {
  182. try {
  183. require('clipboardy').writeSync(urls.localUrlForBrowser)
  184. copied = chalk.dim('(copied to clipboard)')
  185. } catch (_) {
  186. /* catch exception if copy to clipboard isn't supported (e.g. WSL), see issue #3476 */
  187. }
  188. }
  189. const networkUrl = publicUrl
  190. ? publicUrl.replace(/([^/])$/, '$1/')
  191. : urls.lanUrlForTerminal
  192. console.log()
  193. console.log(` App running at:`)
  194. console.log(` - Local: ${chalk.cyan(urls.localUrlForTerminal)} ${copied}`)
  195. if (!isInContainer) {
  196. console.log(` - Network: ${chalk.cyan(networkUrl)}`)
  197. } else {
  198. console.log()
  199. console.log(chalk.yellow(` It seems you are running Vue CLI inside a container.`))
  200. if (!publicUrl && options.publicPath && options.publicPath !== '/') {
  201. console.log()
  202. console.log(chalk.yellow(` Since you are using a non-root publicPath, the hot-reload socket`))
  203. console.log(chalk.yellow(` will not be able to infer the correct URL to connect. You should`))
  204. console.log(chalk.yellow(` explicitly specify the URL via ${chalk.blue(`devServer.public`)}.`))
  205. console.log()
  206. }
  207. console.log(chalk.yellow(` Access the dev server via ${chalk.cyan(
  208. `${protocol}://localhost:<your container's external mapped port>${options.publicPath}`
  209. )}`))
  210. }
  211. console.log()
  212. if (isFirstCompile) {
  213. isFirstCompile = false
  214. if (!isProduction) {
  215. const buildCommand = hasProjectYarn(api.getCwd()) ? `yarn build` : hasProjectPnpm(api.getCwd()) ? `pnpm run build` : `npm run build`
  216. console.log(` Note that the development build is not optimized.`)
  217. console.log(` To create a production build, run ${chalk.cyan(buildCommand)}.`)
  218. } else {
  219. console.log(` App is served in production mode.`)
  220. console.log(` Note this is for preview or E2E testing only.`)
  221. }
  222. console.log()
  223. if (args.open || projectDevServerOptions.open) {
  224. const pageUri = (projectDevServerOptions.openPage && typeof projectDevServerOptions.openPage === 'string')
  225. ? projectDevServerOptions.openPage
  226. : ''
  227. openBrowser(urls.localUrlForBrowser + pageUri)
  228. }
  229. // Send final app URL
  230. if (args.dashboard) {
  231. const ipc = new IpcMessenger()
  232. ipc.send({
  233. vueServe: {
  234. url: urls.localUrlForBrowser
  235. }
  236. })
  237. }
  238. // resolve returned Promise
  239. // so other commands can do api.service.run('serve').then(...)
  240. resolve({
  241. server,
  242. url: urls.localUrlForBrowser
  243. })
  244. } else if (process.env.VUE_CLI_TEST) {
  245. // signal for test to check HMR
  246. console.log('App updated')
  247. }
  248. })
  249. server.listen(port, host, err => {
  250. if (err) {
  251. reject(err)
  252. }
  253. })
  254. })
  255. })
  256. }
  257. function addDevClientToEntry (config, devClient) {
  258. const { entry } = config
  259. if (typeof entry === 'object' && !Array.isArray(entry)) {
  260. Object.keys(entry).forEach((key) => {
  261. entry[key] = devClient.concat(entry[key])
  262. })
  263. } else if (typeof entry === 'function') {
  264. config.entry = entry(devClient)
  265. } else {
  266. config.entry = devClient.concat(entry)
  267. }
  268. }
  269. // https://stackoverflow.com/a/20012536
  270. function checkInContainer () {
  271. const fs = require('fs')
  272. if (fs.existsSync(`/proc/1/cgroup`)) {
  273. const content = fs.readFileSync(`/proc/1/cgroup`, 'utf-8')
  274. return /:\/(lxc|docker|kubepods)\//.test(content)
  275. }
  276. }
  277. function genHistoryApiFallbackRewrites (baseUrl, pages = {}) {
  278. const path = require('path')
  279. const multiPageRewrites = Object
  280. .keys(pages)
  281. // sort by length in reversed order to avoid overrides
  282. // eg. 'page11' should appear in front of 'page1'
  283. .sort((a, b) => b.length - a.length)
  284. .map(name => ({
  285. from: new RegExp(`^/${name}`),
  286. to: path.posix.join(baseUrl, pages[name].filename || `${name}.html`)
  287. }))
  288. return [
  289. ...multiPageRewrites,
  290. { from: /./, to: path.posix.join(baseUrl, 'index.html') }
  291. ]
  292. }
  293. module.exports.defaultModes = {
  294. serve: 'development'
  295. }