serve.js 11 KB

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