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

85.11% Statements 160/188
78.49% Branches 73/93
76% Functions 19/25
86.34% Lines 158/183
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 5641x 1x 1x 1x 1x 1x 1x                 1x 1x 1x   1x     57x       57x       57x     57x   57x         57x 1x     57x                     40x   40x 40x 40x   40x     40x 200x 200x   40x 40x 40x 40x 40x   40x         40x 40x                 40x 40x 1x   1x     39x                   39x 39x   39x   39x         39x   39x 1x 1x           39x   38x                   38x 38x 38x 38x     38x       38x       38x   38x     1x       1x       1x       40x   40x                       40x 40x                 57x                 16x 16x 16x       16x     16x         16x     16x     16x 20x   19x                     19x 19x 19x 19x     19x       19x 19x 19x     1x       1x       1x             16x       16x 4x         4x     4x       4x               16x   16x 17x   4x         4x   4x         16x                     16x 16x     16x                       20x 1x     1x     1x     1x     19x           19x 2x           17x       19x   19x     19x   19x                                     19x   1x 1x     18x     18x         19x 4x   4x 4x 4x     4x 4x                   57x                                         57x                                                           57x 57x 57x 57x 57x           57x   57x       57x   38x         19x         19x             19x 2926x 19x     19x   57x   1x 56x               57x           57x 57x               57x 55x 55x             57x 57x     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
 
  // 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
        const removeArg = (arg, count) => {
          const index = rawArgs.indexOf(arg)
          if (index !== -1) rawArgs.splice(index, count)
        }
        removeArg('--mode', 2)
        removeArg('--dest', 2)
        removeArg('--legacy', 1)
        removeArg('--dashboard', 1)
        removeArg('--skipBundle', 1)
        // 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 {
          //   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: outputDir + '/bundled',
            // Enable modern mode unless --legacy is passed
            modern: !args.legacy
          }
          //   Set the base url so that the app protocol is used
          options.baseUrl = pluginOptions.noAppProtocol ? './' : '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
          fs.copySync(
            api.resolve('./package.json'),
            `${outputDir}/bundled/package.json`
          )
          // 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 => {
      // Use custom config for webpack
      process.env.IS_ELECTRON = true
      const execa = require('execa')
      const mainProcessWatch = [
        mainProcessFile,
        ...(pluginOptions.mainProcessWatch || [])
      ]
      const mainProcessArgs = pluginOptions.mainProcessArgs || []
 
      // 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 = () => {
        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()
        }
      }
 
      // Electron process
      let child
      // Auto restart flag
      let childRestartOnExit = 0
      // Graceful exit timeout
      let childExitTimeout
      // Function to kill Electron process
      const killElectron = () => {
        Iif (!child) {
          return
        }
 
        // Attempt to kill gracefully
        Iif (process.platform === 'win32') {
          child.send('graceful-exit')
        } else {
          child.kill('SIGTERM')
        }
 
        // Kill unconditionally after 2 seconds if unsuccessful
        childExitTimeout = setTimeout(() => {
          if (child) {
            child.kill('SIGKILL')
          }
        }, 2000)
      }
 
      // Initial start of Electron
      startElectron()
      // Restart on main process file change
      mainProcessWatch.forEach(file => {
        fs.watchFile(api.resolve(file), () => {
          // Never restart after SIGINT
          Iif (childRestartOnExit < 0) {
            return
          }
 
          // Set auto restart flag
          childRestartOnExit = 1
 
          killElectron()
        })
      })
 
      // Attempt to kill gracefully on SIGINT and SIGTERM
      const signalHandler = () => {
        if (!child) {
          process.exit(0)
        }
 
        // Prevent future restarts
        childRestartOnExit = -1
 
        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 () {
        if (args.debug) {
          console.log(info)
 
          //   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(' ') +
                '" ...'
            )
          } else {
            info('Launching Electron...')
          }
 
          // Disable Electron process auto restart
          childRestartOnExit = 0
 
          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
            ],
            {
              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', () => {
            child = null
 
            Eif (childExitTimeout) {
              clearTimeout(childExitTimeout)
              childExitTimeout = null
            }
 
            Eif (childRestartOnExit > 0) {
              startElectron()
            } else {
              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')
  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'))
      }
    ])
    const envVars = {
      // Dev server url
      WEBPACK_DEV_SERVER_URL: server.url,
      // Path to node_modules (for externals in development)
      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')