【问题标题】:Prevent emitting certain code when using webpack to deploy Electron app for the web防止在使用 webpack 为 web 部署 Electron 应用程序时发出某些代码
【发布时间】:2018-09-26 19:34:28
【问题描述】:

我有一个用 TypeScript 编写的基于 Electron 的应用程序。为了捆绑我在我的 gulpfile 中运行 webpack 的代码,它当然可以针对 Electron 或浏览器。各自的配置如下:

const appCompile = gulp.src(`${sourceFolder}/Typescript/Main.ts`)
    .pipe(webpackStream({
        module: {
            rules: [
                {
                    loaders: ["babel-loader", "ts-loader"],
                    exclude: [/node_modules/]
                },
            ]
        },
        resolve: {
            modules: ["Source/Typescript", "node_modules"],
            extensions: [".tsx", ".ts", ".js"]
        },
        output: {
            filename: "Bundle.js"
        },
        mode: buildConfiguration.isDevelopment ? "development" : "production",
        externals: externals,
        target: targetPlatform.isWeb ? "web" : "electron-renderer",
        devtool: buildConfiguration.isDevelopment ? "source-map" : "none"
    }, webpack))
    .pipe(gulp.dest(paths.scripts.dest));

目前我有一些代码行只打算在开发模式下执行,在 Electrons 渲染器(不是主!)进程中本地运行(因为它包含一些低级 fs 代码)。在运行 webpack 为 web 部署时,有什么方法可以防止发出这些行/调用?像 if (isElectron) { doSomethingLocally(); } 这样的语句的全局常量。

编辑:特别是像 import * as fs from "fs"; 这样的导入错误,当为 web 而不是 Electron 打包时,正如预期的那样。即使我可以使用像 const isElectron = navigator.userAgent.indexOf("Electron") !== -1; 这样的助手,这也不会帮助我“有条件地导入”。

【问题讨论】:

    标签: typescript webpack gulp electron


    【解决方案1】:

    Webpack 有node 配置对象,当目标是web 时,你可以告诉它what to do with built-in node modules and objects

    例如,如果您希望 import * as fs from "fs"; 导致 fs 成为 undefined,您可以尝试将此行添加到 webpack 配置:

    node: targetPlatform.isWeb ? {fs: 'empty'} : undefined,
    

    然后,在运行时,您可以检查结果并避免使用未定义的 fs 方法:

    import * as fs from "fs";
    
    if (fs.writeFile) {
    }
    

    【讨论】:

    • 使用您建议的解决方案,它已成功转译,但浏览器在尝试调用 fs.writeFile 之类的方法时仍会引发异常。 fs 对象似乎既不是 null、false 也不是 undefined。
    • 在这种情况下fs 是空对象,{}。我更新了答案。你也可以这样查看if (Object.keys(fs).length !== 0) {}
    • 我刚刚遇到了一个使用适当 ES6 的更好的解决方案:stackoverflow.com/a/46543835/796036 - 使用这种方法,我可以将所有关键代码封装在一个模块中,我可以有条件地导入,而无需手动添加所有使用过的代码节点模块到 webpack 配置。不过还是谢谢你。
    猜你喜欢
    • 2019-08-27
    • 2023-03-27
    • 1970-01-01
    • 2012-02-13
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    相关资源
    最近更新 更多