typescript - 使用Webpack为Web部署Electron应用程序时防止发出某些代码

标签 typescript webpack gulp electron

我有一个用TypeScript编写的基于 Electron 的应用程序。为了 bundle 代码,我在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渲染器(不是main!)进程中本地运行的开发模式下执行(因为它包含一些低级的fs代码)。运行webpack部署到Web时,是否有任何方法可以防止发出这些线路/调用?诸如if (isElectron) { doSomethingLocally(); }之类的语句的全局常量之类的东西。

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

最佳答案

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

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

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

然后,在运行时,您可以检查结果,并避免使用fs方法(如果未定义):
import * as fs from "fs";

if (fs.writeFile) {
}

关于typescript - 使用Webpack为Web部署Electron应用程序时防止发出某些代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49867855/

相关文章:

angular - 类型 'unknown' 无法分配给类型 'KeyboardEvent' .ts (2345)

Webpack 和 PostCSS Autoprefixer 不编译 Sass 部分

javascript - gulp watchify 需要两次保存才能包含更改

node.js - typescript 错误找不到名称 'require'。 ionic 3

visual-studio - VS2017 在保存时需要很长时间重新编译 typescript

typescript - NestJS - 如何使用@Body() 装饰器访问帖子正文?

typescript - IE 11 - 抛出 'webpackJsonp' 未定义

typescript - 带有 TypeScript + Angular 2 的 Protractor 配置错误

javascript - gulp.watch() 不适用于 ftp 更新

javascript - 使用 gulp-sourcemaps 的文件名不正确