Search code examples
javascriptwebpackelectronwebpack-2

Configure Webpack with Electron to use ES6 imports?


I am trying to use Webpack since I want to use ES modules in my Electron application but having some hurdles. I just want to use import in my main as well as renderer processes.

My application structure is as follows -

- src/                  // contains basic html, css & js
  - index.html          // <h1>Hello World</h1>
  - style.css           // is empty
  - app.js              // console.log('it works 🙈')
- app/                  // contains electron code
  - main_window.js
  - custom_tray.js
- index.js              // entry point for electron application
- dist/                 // output bundle generated from webpack
  - bundle.js

My index.js file looks like -

import path from "path";
import { app } from "electron";

import MainWindow from "./app/main_window";
import CustomTray from "./app/custom_tray";

let win = null,
    tray = null;

app.on("ready", () => {
    // app.dock.hide();
    win = new MainWindow(path.join("file://", __dirname, "/src/index.html"));

    win.on("closed", () => {
        win = null;
    });

    tray = new CustomTray(win);
});

My main_window.js file looks like -

import { BrowserWindow } from "electron";

const config = {
    width: 250,
    height: 350,
    show: false,
    frame: false,
    radii: [500, 500, 500, 500],
    resizable: false,
    fullscreenable: false
};

class MainWindow extends BrowserWindow {
    constructor(url) {
        super(config);

        this.loadURL(url);
        this.on("blur", this.onBlur);
        this.show();
    }

    onBlur = () => {
        this.hide();
    };
}

export default MainWindow;

My custom_tray.js looks like -

import path from "path";
import { app, Tray, Menu } from "electron";

const iconPath = path.join(__dirname, "../src/assets/iconTemplate.png");

class CustomTray extends Tray {
    constructor(mainWindow) {
        super(iconPath);
        this.mainWindow = mainWindow;

        this.setToolTip("Thirsty");

        this.on("click", this.onClick);
        this.on("right-click", this.onRightClick);
    }

    onClick = (event, bounds) => {
        const { x, y } = bounds;
        const { width, height } = this.mainWindow.getBounds();

        const isMac = process.platform === "darwin";

        if (this.mainWindow.isVisible()) {
            this.mainWindow.hide();
        } else {
            this.mainWindow.setBounds({
                x: x - width / 2,
                y: isMac ? y : y - height,
                width,
                height
            });
            this.mainWindow.show();
        }
    };

    onRightClick = () => {
        const menuConfig = Menu.buildFromTemplate([
            {
                label: "Quit",
                click: () => app.quit()
            }
        ]);
        this.popUpContextMenu(menuConfig);
    };
}

export default CustomTray;

And my webpack.main.config.js looks like -

const path = require("path");

const config = {
    entry: "./index.js",
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js"
    },
    module: {
        rules: [{ test: /\.js$/, exclude: /node_modules/, use: "babel-loader" }]
    },
    stats: {
        colors: true
    },
    target: "electron-main",
    devtool: "source-map"
};

module.exports = config;

And my webpack.renderer.config.js looks like -

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");

const config = {
    entry: "./src/app.js",
    output: {
        path: path.resolve(__dirname, "dist/renderer"),
        filename: "app.js"
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: "babel-loader"
            },
            {
                test: /\.css$/,
                use: {
                    loader: "css-loader",
                    options: {
                        minimize: true
                    }
                }
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                use: {
                    loader: "url-loader",
                    query: {
                        limit: 10000,
                        name: "imgs/[name].[ext]"
                    }
                }
            },
            {
                test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                use: {
                    loader: "url-loader",
                    query: {
                        limit: 10000,
                        name: "fonts/[name].[ext]"
                    }
                }
            }
        ]
    },
    stats: {
        colors: true
    },
    target: "electron-renderer",
    devtool: "source-map",
    plugins: [
        new CopyWebpackPlugin([
            { from: "src/app.css" },
            { from: "src/assets", to: "assets/" }
        ]),
        new HtmlWebpackPlugin({
            filename: "index.html",
            template: path.resolve(__dirname, "./src/index.html"),
            minify: {
                collapseWhitespace: true,
                removeAttributeQuotes: true,
                removeComments: true
            }
        })
    ]
};

module.exports = config;

My scripts in package.json look like

"scripts": {
    "dev:main": "webpack --mode development --config webpack.main.config.js",
    "dev:renderer": "webpack --mode development --config webpack.renderer.config.js",
    "dev:all": "npm run dev:main && npm run dev:renderer",
    "build:main": "webpack --mode production --config webpack.main.config.js",
    "build:renderer": "webpack --mode production --config webpack.renderer.config.js",
    "build:all": "npm run build:main && npm run build:renderer",
    "prestart": "npm run build:all",
    "electron": "electron dist/index.js",
    "start": "npm run electron",
}

Currently my application creates a dist/bundle.js but when I run electron dist/bundle.js it doesn't work. I get it, it might be because it does not contain src folder but when I copy src folder into dist it still doesn't work.

Firstly, I run npm run dev:main to generate dist/bundle.js then I run npm run dev:renderer to generate dist/renderer/bundle.js & then I run npm run start to start my electron application.

It gives me error "Uncaught Exception: Error: Requires constructor call at new MainWindow" which is in index.js where I call constructor new MainWindow()

I just want to use ES6 in all my JS files. Is there any boilerplate because the ones I found have tons of additional stuff like React JS & all plus a huge number of optimizations ?


Solution

  • After 8 days I found the answer finally. It works with ESM in Electron.

    I've made a repo that is minimum & lets you write ESM with Electron.

    The complete code can be found at https://github.com/deadcoder0904/electron-webpack-sample

    Its very minimal so it should be easy to understand.