【Electron 快速入门-5.3】Webpack 处理主进程

1,013 阅读1分钟

添加相关依赖

yarn add webpack-merge@4 terser-webpack-plugin@4 webpack-cli@4 webpack@4 babel-loader@8.1.0 -D

添加 base webpack 配置文件

  • config/webpack.base.js
/**

 * Base webpack config used across other specific configs

 */



 const path  = require('path');

 const webpack = require('webpack');

 module.exports = {

   module: {

     rules: [

       {

         test: /.tsx?$/,

         exclude: /node_modules/,

         use: {

           loader: 'babel-loader',

           options: {

             cacheDirectory: true,

           },

         },

       },

     ],

   },

 

   output: {

     path: path.join(__dirname, '../electron'),

     libraryTarget: 'commonjs2',

   },

 

   resolve: {

     extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],

   },

 

   plugins: [

     new webpack.EnvironmentPlugin({

       NODE_ENV: 'production',

     }),

   ],

 };

 

添加主进程 webpack 配置文件

  • config/webpack.main.js
const webpack = require('webpack');

const path = require('path');

const { merge } = require('webpack-merge');

const TerserPlugin = require('terser-webpack-plugin')

const baseConfig = require('./webpack.base');



module.exports = merge(baseConfig, {



  mode: 'production',



  target: 'electron-main',



  entry: './electron/main.ts',



  output: {

    path: path.join(__dirname, '..'),

    filename: './.electron-main/main.prod.js',

  },



  optimization: {

    minimizer: [

      new TerserPlugin({

        parallel: true,

      }),

    ]

  },



  plugins: [

    new webpack.EnvironmentPlugin({

      NODE_ENV: 'production',

      DEBUG_PROD: false,

      START_MINIMIZED: false,

    }),

  ],



  node: {

    __dirname: false,

    __filename: false,

  },

});

gitignore 中忽略 .electron-main 产物目录

添加编译命令

{

    "build:main": "webpack --config ./config/webpack.main.js",

}

打包的时候 create-react 会提示如下几个包版本问题,修改版本号和其统一,重新 install 即可。

  • webpack@4.44.2
  • babel-loader@8.1.0