【问题标题】:How to call function bundled by Webpack in Electron main js script如何在 Electron 主 js 脚本中调用 Webpack 捆绑的函数
【发布时间】:2020-11-07 00:22:59
【问题描述】:

我正在尝试从我的 (webpack'ed) 包中访问一个函数,但该函数未定义。 (整个对象为空)(在 electron-main.js 中参见 appBundle.test()

我一直在网上搜索,但找不到我正在寻找的答案。 尝试了所有不同的 libraryTarget 选项,但没有一个按我预期的方式工作。

这里是源代码:

webpack.dev.js:

...

module.exports = Merge(CommonConfig, {
    devtool: "inline-source-map",
    watch: true,

    entry: path.resolve(__dirname, "src/index.ts"),

    output: {
        filename: "bundle.js",
        path: __dirname + "/wwwroot/resources/js/components",
        publicPath: "/resources/js/components/",
        library: "appBundle",
        libraryTarget: "commonjs2"
    },

    plugins: ([
        new webpack.DefinePlugin({
            "process.env": {
                "NODE_ENV": JSON.stringify("development")
            }
        }),

        // Etract CSS
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css',
        }),
    ]),
})

index.ts:

import 'react-app-polyfill/ie11';
import 'react-app-polyfill/stable';

// Styling
import './application-styling.scss';

// Application
import "./application/index.tsx";

export default function test() {
    console.log('hello');
}

electron-main.js:

const { BrowserWindow } = require('electron');

const createAppWindow = require('../main/app-process');
const authService = require('../services/auth-service');

global.window = {}; // <- Need to define this manually, else the require call throws errors

const appBundle = require('app-bundle'); // Trying to import the bundle.js here

let win = null;

function createAuthWindow() {
    destroyAuthWin();

    win = new BrowserWindow({
        width: 1000,
        height: 600,
        webPreferences: {
            nodeIntegration: false,
            enableRemoteModule: false
        }
    });

    win.loadURL(authService.getAuthenticationURL());

    const { session: { webRequest } } = win.webContents;

    const filter = {
        urls: [
            'http://localhost/callback*'
        ]
    };

    webRequest.onBeforeRequest(filter, async ({ url }) => {

        console.log(appBundle); // <- undefined or empty object, depending on libraryTarget
        console.log(appBundle.test()); // <- error, test is undefined

        await authService.loadTokens(url);
        createAppWindow();
        return destroyAuthWin();
    });
    ...
}


...

【问题讨论】:

    标签: javascript node.js webpack electron commonjs


    【解决方案1】:

    显然import "./application/index.tsx"; 调用以某种方式弄乱了导出。当我只是使用一个干净的文件作为入口点时,它工作得很好。

    无论如何,我最终只是将电子项目与应用程序包一起构建到一个包中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-17
      • 2018-07-03
      • 1970-01-01
      • 2018-03-12
      • 2021-03-25
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多