I have a Electron-based app written in TypeScript. To bundle the code I am running webpack in my gulpfile which can either target Electron or the browser of course. The respective configuration looks as follows:
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));
Currently I have some lines of code only meant to be executed in development mode running locally in Electrons renderer (not main!) process (since it includes some low-level fs code). Is there any way to prevent emitting those lines/calls when running webpack to deploy for the web? Something like global constants for statements like if (isElectron) { doSomethingLocally(); }
.
EDIT: Especially imports like import * as fs from "fs";
error as expected when packing for the web instead of Electron. Even though I can use a helper like const isElectron = navigator.userAgent.indexOf("Electron") !== -1;
this won't help me to "conditionally import".
Webpack has node
configuration object, where you can tell it what to do with built-in node modules and objects when target is web
.
For example, if you want import * as fs from "fs";
to result in fs
being undefined
, you can try adding this line to webpack config:
node: targetPlatform.isWeb ? {fs: 'empty'} : undefined,
Then, at runtime, you can check the result and avoid using fs
methods if they are undefined:
import * as fs from "fs";
if (fs.writeFile) {
}