All files / vue-cli-plugin-electron-builder index.js

87.08% Statements 182/209
82.18% Branches 83/101
74.07% Functions 20/27
88.67% Lines 180/203

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 5981x 1x 1x 1x 1x 1x 1x                 1x 1x 1x   1x     77x       77x       77x     77x   77x       77x 318x 318x       77x 1x     77x                     45x   45x 45x 45x   45x     45x 45x 45x 45x 45x   45x         45x 45x                 45x 45x 1x   1x   44x   44x                   44x   44x 44x   44x 44x 46x   2x   46x           44x   44x 44x   44x   44x     44x     44x 2x 1x     44x         44x   44x 1x 1x           44x   43x                   43x 43x 43x 43x     43x       43x       43x   43x     1x       1x       1x       45x   45x                       45x 45x                 77x                 31x 31x 31x       31x     31x 31x 31x     31x         31x     31x     31x 35x 35x   34x                     34x 34x 34x 34x     34x       34x 34x 34x     1x       1x       1x         31x     31x   31x 35x 31x     4x     4x     4x       4x                 31x   31x 31x 32x   4x 4x           31x               31x 31x     31x                       35x   35x 4x     35x   35x 35x   35x   1x     1x     1x     34x           34x 2x               32x     34x     34x   34x                                         34x   1x 1x     33x     33x         34x                   77x                                         77x                                                           77x 77x 77x 77x 77x           77x   77x       77x 77x   43x         34x           34x   34x     77x 13208x 41x     77x   77x   1x 76x               77x           77x 77x               77x 75x 75x             77x 77x     1x           1x  
const TerserPlugin = require('terser-webpack-plugin')
const webpack = require('webpack')
const Config = require('webpack-chain')
const merge = require('lodash.merge')
const fs = require('fs-extra')
const path = require('path')
const readline = require('readline')
const {
  log,
  done,
  info,
  logWithSpinner,
  stopSpinner,
  warn,
  error
} = require('@vue/cli-shared-utils')
const formatStats = require('@vue/cli-service/lib/commands/build/formatStats')
const { chainWebpack, getExternals } = require('./lib/webpackConfig')
 
module.exports = (api, options) => {
  // If plugin options are provided in vue.config.js, those will be used. Otherwise it is empty object
  const pluginOptions =
    options.pluginOptions && options.pluginOptions.electronBuilder
      ? options.pluginOptions.electronBuilder
      : {}
  // If option is not set in pluginOptions, default is used
  const usesTypescript = pluginOptions.disableMainProcessTypescript
    ? false
    : api.hasPlugin('typescript')
  const mainProcessFile =
    pluginOptions.mainProcessFile ||
    (usesTypescript ? 'src/background.ts' : 'src/background.js')
  const mainProcessChain =
    pluginOptions.chainWebpackMainProcess || (config => config)
  const bundleMainProcess =
    pluginOptions.bundleMainProcess == null
      ? true
      : pluginOptions.bundleMainProcess
 
  const removeArg = (arg, count, rawArgs) => {
    const index = rawArgs.indexOf(arg)
    if (index !== -1) rawArgs.splice(index, count)
  }
 
  // Apply custom webpack config
  api.chainWebpack(async config => {
    chainWebpack(api, pluginOptions, config)
  })
 
  api.registerCommand(
    'electron:build',
    {
      description: 'build app with electron-builder',
      usage: 'vue-cli-service build:electron [electron-builder options]',
      details:
        `All electron-builder command line options are supported.\n` +
        `See https://www.electron.build/cli for cli options\n` +
        `See https://nklayman.github.io/vue-cli-plugin-electron-builder/ for more details about this plugin.`
    },
    (args, rawArgs) =>
      new Promise(async (resolve, reject) => {
        // Use custom config for webpack
        process.env.IS_ELECTRON = true
        const builder = require('electron-builder')
        const yargs = require('yargs')
        //   Import the yargs options from electron-builder
        const configureBuildCommand = require('electron-builder/out/builder')
          .configureBuildCommand
        // Prevent custom args from interfering with electron-builder
        removeArg('--mode', 2, rawArgs)
        removeArg('--dest', 2, rawArgs)
        removeArg('--legacy', 1, rawArgs)
        removeArg('--dashboard', 1, rawArgs)
        removeArg('--skipBundle', 1, rawArgs)
        // Parse the raw arguments using electron-builder yargs config
        const builderArgs = yargs
          .command(['build', '*'], 'Build', configureBuildCommand)
          .parse(rawArgs)
        //   Base config used in electron-builder build
        const outputDir =
          args.dest || pluginOptions.outputDir || 'dist_electron'
        const defaultBuildConfig = {
          directories: {
            output: outputDir,
            app: `${outputDir}/bundled`
          },
          files: ['**'],
          extends: null
        }
        //   User-defined electron-builder config, overwrites/adds to default config
        const userBuildConfig = pluginOptions.builderOptions || {}
        if (args.skipBundle) {
          console.log('Not bundling app as --skipBundle was passed')
          // Build with electron-builder
          buildApp()
        } else {
          const bundleOutputDir = path.join(outputDir, 'bundled')
          //   Arguments to be passed to renderer build
          const vueArgs = {
            _: [],
            // For the cli-ui webpack dashboard
            dashboard: args.dashboard,
            // Make sure files are outputted to proper directory
            dest: bundleOutputDir,
            // Enable modern mode unless --legacy is passed
            modern: !args.legacy
          }
          // With @vue/cli-service v3.4.1+, we can bypass legacy build
          process.env.VUE_CLI_MODERN_BUILD = !args.legacy
          // If the legacy builded is skipped the output dir won't be cleaned
          fs.removeSync(bundleOutputDir)
          fs.ensureDirSync(bundleOutputDir)
          // Mock data from legacy build
          const pages = options.pages || { index: '' }
          Object.keys(pages).forEach(page => {
            if (pages[page].filename) {
              // If page is configured as an object, use the filename (without .html)
              page = pages[page].filename.replace(/\.html$/, '')
            }
            fs.writeFileSync(
              path.join(bundleOutputDir, `legacy-assets-${page}.html.json`),
              '[]'
            )
          })
          //   Set the base url so that the app protocol is used
          options.baseUrl = pluginOptions.customFileProtocol || 'app://./'
          // Set publicPath as well (replaced baseUrl since @vue/cli 3.3.0)
          options.publicPath = pluginOptions.customFileProtocol || 'app://./'
          info('Bundling render process:')
          //   Build the render process with the custom args
          await api.service.run('build', vueArgs)
          // Copy package.json to output dir
          const pkg = JSON.parse(
            fs.readFileSync(api.resolve('./package.json'), 'utf8')
          )
          const externals = getExternals(api, pluginOptions)
          // https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/223
          // Strip non-externals from dependencies so they won't be copied into app.asar
          Object.keys(pkg.dependencies).forEach(dependency => {
            if (!Object.keys(externals).includes(dependency)) {
              delete pkg.dependencies[dependency]
            }
          })
          fs.writeFileSync(
            `${outputDir}/bundled/package.json`,
            JSON.stringify(pkg, 2)
          )
          // Prevent electron-builder from installing app deps
          fs.ensureDirSync(`${outputDir}/bundled/node_modules`)
          //   Copy fonts to css/fonts. Fixes some issues with static font imports
          if (fs.existsSync(api.resolve(outputDir + '/bundled/fonts'))) {
            fs.ensureDirSync(api.resolve(outputDir + '/bundled/css/fonts'))
            fs.copySync(
              api.resolve(outputDir + '/bundled/fonts'),
              api.resolve(outputDir + '/bundled/css/fonts')
            )
          }
 
          if (bundleMainProcess) {
            //   Build the main process into the renderer process output dir
            const bundle = bundleMain({
              mode: 'build',
              api,
              args,
              pluginOptions,
              outputDir,
              mainProcessFile,
              mainProcessChain,
              usesTypescript
            })
            logWithSpinner('Bundling main process...')
            bundle.run((err, stats) => {
              stopSpinner(false)
              Iif (err) {
                return reject(err)
              }
              Iif (stats.hasErrors()) {
                // eslint-disable-next-line prefer-promise-reject-errors
                return reject(`Build failed with errors.`)
              }
              const targetDirShort = path.relative(
                api.service.context,
                `${outputDir}/bundled`
              )
              log(formatStats(stats, targetDirShort, api))
 
              buildApp()
            })
          } else {
            info(
              'Not bundling main process as bundleMainProcess was set to false in plugin options'
            )
            // Copy main process file instead of bundling it
            fs.copySync(
              api.resolve(mainProcessFile),
              api.resolve(`${outputDir}/bundled/background.js`)
            )
            buildApp()
          }
        }
        function buildApp () {
          info('Building app with electron-builder:')
          // Build the app using electron builder
          builder
            .build({
              //   Args parsed with yargs
              ...builderArgs,
              config: merge(
                defaultBuildConfig,
                //   User-defined config overwrites defaults
                userBuildConfig
              )
            })
            .then(() => {
              // handle result
              done('Build complete!')
              resolve()
            })
            .catch(err => {
              // handle error
              return reject(err)
            })
        }
      })
  )
  api.registerCommand(
    'electron:serve',
    {
      description: 'serve app and launch electron',
      usage: 'vue-cli-service serve:electron',
      details: `See https://nklayman.github.io/vue-cli-plugin-electron-builder/ for more details about this plugin.`
    },
    async (args, rawArgs) => {
      // Use custom config for webpack
      process.env.IS_ELECTRON = true
      const execa = require('execa')
      const mainProcessWatch = [
        mainProcessFile,
        ...(pluginOptions.mainProcessWatch || [])
      ]
      const mainProcessArgs = pluginOptions.mainProcessArgs || []
 
      // Don't pass command args to electron
      removeArg('--dashboard', 1, rawArgs)
      removeArg('--debug', 1, rawArgs)
      removeArg('--headless', 1, rawArgs)
 
      // Run the serve command
      const server = await api.service.run('serve', {
        _: [],
        // Use dashboard if called from ui
        dashboard: args.dashboard
      })
      const outputDir = pluginOptions.outputDir || 'dist_electron'
 
      // Copy package.json so electron can detect app's name
      fs.copySync(api.resolve('./package.json'), `${outputDir}/package.json`)
 
      // Function to bundle main process and start Electron
      const startElectron = () => {
        queuedBuilds++
        if (bundleMainProcess) {
          //   Build the main process
          const bundle = bundleMain({
            mode: 'serve',
            api,
            args,
            pluginOptions,
            outputDir,
            mainProcessFile,
            mainProcessChain,
            usesTypescript,
            server
          })
          logWithSpinner('Bundling main process...')
          bundle.run((err, stats) => {
            stopSpinner(false)
            Iif (err) {
              throw err
            }
            Iif (stats.hasErrors()) {
              error(`Build failed with errors.`)
              process.exit(1)
            }
            const targetDirShort = path.relative(api.service.context, outputDir)
            log(formatStats(stats, targetDirShort, api))
            launchElectron()
          })
        } else {
          info(
            'Not bundling main process as bundleMainProcess was set to false in plugin options'
          )
          // Copy main process file instead of bundling it
          fs.copySync(
            api.resolve(mainProcessFile),
            api.resolve(`${outputDir}/index.js`)
          )
          launchElectron()
        }
      }
 
      // Prevent multiple restarts at the same time
      let queuedBuilds = 0
      // Electron process
      let child
      let firstBundleCompleted = false
      // Function to kill Electron process
      const killElectron = () => {
        if (!child) {
          return
        }
 
        const currentChild = child
 
        // Attempt to kill gracefully
        Iif (process.platform === 'win32') {
          currentChild.send('graceful-exit')
        } else {
          currentChild.kill('SIGTERM')
        }
 
        // Kill unconditionally after 2 seconds if unsuccessful
        setTimeout(() => {
          if (!currentChild.killed) {
            warn(`Force killing Electron (process #${currentChild.pid})`)
            currentChild.kill('SIGKILL')
          }
        }, 2000)
      }
 
      // Initial start of Electron
      startElectron()
      // Restart on main process file change
      const chokidar = require('chokidar')
      mainProcessWatch.forEach(file => {
        chokidar.watch(api.resolve(file)).on('all', () => {
          // This function gets triggered on first launch
          Eif (firstBundleCompleted) {
            startElectron()
          }
        })
      })
 
      // Attempt to kill gracefully on SIGINT and SIGTERM
      const signalHandler = () => {
        if (!child) {
          process.exit(0)
        }
 
        killElectron()
      }
 
      Iif (!process.env.IS_TEST) process.on('SIGINT', signalHandler)
      Iif (!process.env.IS_TEST) process.on('SIGTERM', signalHandler)
 
      // Handle Ctrl+C on Windows
      Iif (process.platform === 'win32' && !process.env.IS_TEST) {
        readline
          .createInterface({
            input: process.stdin,
            output: process.stdout
          })
          .on('SIGINT', () => {
            process.emit('SIGINT')
          })
      }
 
      function launchElectron () {
        firstBundleCompleted = true
        // Don't exit process when electron is killed
        if (child) {
          child.removeListener('exit', onChildExit)
        }
        // Kill existing instances
        killElectron()
        // Don't launch if a new background file is being bundled
        queuedBuilds--
        Iif (queuedBuilds > 0) return
 
        if (args.debug) {
          //   Do not launch electron and provide instructions on launching through debugger
          info(
            'Not launching electron as debug argument was passed. You must launch electron though your debugger.'
          )
          info(
            `If you are using Spectron, make sure to set the IS_TEST env variable to true.`
          )
          info(
            'Learn more about debugging the main process at https://nklayman.github.io/vue-cli-plugin-electron-builder/guide/testingAndDebugging.html#debugging.'
          )
        } else Iif (args.headless) {
          // Log information for spectron
          console.log(`$outputDir=${outputDir}`)
          console.log(`$WEBPACK_DEV_SERVER_URL=${server.url}`)
        } else {
          // Launch electron with execa
          if (mainProcessArgs.length > 0) {
            info(
              'Launching Electron with arguments: "' +
                mainProcessArgs.join(' ') +
                ' ' +
                rawArgs.join(' ') +
                '" ...'
            )
          } else {
            info('Launching Electron...')
          }
 
          let stdioConfig = [null, null, null]
 
          // Use an IPC on Windows for graceful exit
          Iif (process.platform === 'win32') stdioConfig.push('ipc')
 
          child = execa(
            require('electron'),
            [
              // Have it load the main process file built with webpack
              outputDir,
              // Append other arguments specified in plugin options
              ...mainProcessArgs,
              // Append args passed to command
              ...rawArgs
            ],
            {
              cwd: api.resolve('.'),
              env: {
                ...process.env,
                // Disable electron security warnings
                ELECTRON_DISABLE_SECURITY_WARNINGS: true
              },
              stdio: stdioConfig
            }
          )
 
          if (pluginOptions.removeElectronJunk === false) {
            // Pipe output to console
            child.stdout.pipe(process.stdout)
            child.stderr.pipe(process.stderr)
          } else {
            // Remove junk terminal output (#60)
            child.stdout
              .pipe(require('./lib/removeJunk.js')())
              .pipe(process.stdout)
            child.stderr
              .pipe(require('./lib/removeJunk.js')())
              .pipe(process.stderr)
          }
 
          child.on('exit', onChildExit)
        }
      }
 
      function onChildExit () {
        process.exit(0)
      }
    }
  )
 
  api.registerCommand(
    'build:electron',
    {
      description:
        '[deprecated, use electron:build instead] build app with electron-builder',
      usage: 'vue-cli-service build:electron [electron-builder options]',
      details:
        `All electron-builder command line options are supported.\n` +
        `See https://www.electron.build/cli for cli options\n` +
        `See https://nklayman.github.io/vue-cli-plugin-electron-builder/ for more details about this plugin.`
    },
    (args, rawArgs) => {
      warn('This command is deprecated. Please use electron:build instead.')
      return api.service.run(
        'electron:build',
        { ...args, _: ['First arg is removed', ...args._] },
        ['First arg is removed', ...rawArgs]
      )
    }
  )
 
  api.registerCommand(
    'serve:electron',
    {
      description:
        '[deprecated, use electron:serve instead] serve app and launch electron',
      usage: 'vue-cli-service serve:electron',
      details: `See https://nklayman.github.io/vue-cli-plugin-electron-builder/ for more details about this plugin.`
    },
    (args, rawArgs) => {
      warn('This command is deprecated. Please use electron:serve instead.')
      return api.service.run(
        'electron:serve',
        { ...args, _: ['First arg is removed', ...args._] },
        ['First arg is removed', ...rawArgs]
      )
    }
  )
}
 
function bundleMain ({
  mode,
  api,
  args,
  pluginOptions,
  outputDir,
  mainProcessFile,
  mainProcessChain,
  usesTypescript,
  server
}) {
  const mainProcessTypeChecking = pluginOptions.mainProcessTypeChecking || false
  const isBuild = mode === 'build'
  const NODE_ENV = process.env.NODE_ENV
  const config = new Config()
  config
    .mode(NODE_ENV)
    .target('electron-main')
    .node.set('__dirname', false)
    .set('__filename', false)
  // Set externals
  config.externals(getExternals(api, pluginOptions))
 
  config.output
    .path(api.resolve(outputDir + (isBuild ? '/bundled' : '')))
    // Electron will not detect background.js on dev server, only index.js
    .filename('[name].js')
  const envVars = {}
  if (isBuild) {
    //   Set __static to __dirname (files in public get copied here)
    config
      .plugin('define')
      .use(webpack.DefinePlugin, [{ __static: '__dirname' }])
  } else {
    // Set __static to public folder
    config.plugin('define').use(webpack.DefinePlugin, [
      {
        __static: JSON.stringify(api.resolve('./public'))
      }
    ])
    // Dev server url
    envVars['WEBPACK_DEV_SERVER_URL'] = server.url
    // Path to node_modules (for externals in development)
    envVars['NODE_MODULES_PATH'] = api.resolve('./node_modules')
  }
  // Add all env vars prefixed with VUE_APP_
  Object.keys(process.env).forEach(k => {
    if (/^VUE_APP_/.test(k)) {
      envVars[k] = process.env[k]
    }
  })
  config.plugin('env').use(webpack.EnvironmentPlugin, [envVars])
 
  if (args.debug) {
    // Enable source maps for debugging
    config.devtool('source-map')
  } else Iif (NODE_ENV === 'production') {
    // Minify for better performance
    config.plugin('uglify').use(TerserPlugin, [
      {
        parallel: true
      }
    ])
  }
  config
    .entry(isBuild ? 'background' : 'index')
    .add(api.resolve(mainProcessFile))
  const {
    transformer,
    formatter
  } = require('@vue/cli-service/lib/util/resolveLoaderError')
  config
    .plugin('friendly-errors')
    .use(require('friendly-errors-webpack-plugin'), [
      {
        additionalTransformers: [transformer],
        additionalFormatters: [formatter]
      }
    ])
  if (usesTypescript) {
    config.resolve.extensions.merge(['.js', '.ts'])
    config.module
      .rule('ts')
      .test(/\.ts$/)
      .use('ts-loader')
      .loader('ts-loader')
      .options({ transpileOnly: !mainProcessTypeChecking })
  }
  mainProcessChain(config)
  return webpack(config.toConfig())
}
 
module.exports.defaultModes = {
  'build:electron': 'production',
  'serve:electron': 'development',
  'electron:build': 'production',
  'electron:serve': 'development'
}
module.exports.testWithSpectron = require('./lib/testWithSpectron')