Giter Site home page Giter Site logo

bytenode-webpack-plugin's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

bytenode-webpack-plugin's Issues

How do I use JS Obfuscator with this?

Added it in the plugins doesn't seem to be obfuscating the JS compiled file.

const { BytenodeWebpackPlugin } = require('@herberttn/bytenode-webpack-plugin')
var WebpackObfuscator = require('webpack-obfuscator')
const rules = require('./webpack.rules')


module.exports = {
  entry: { index: './src/main.ts' },
  output: {
    filename: '[name].js',
    devtoolModuleFilenameTemplate: '[absolute-resource-path]'
  },
  module: {
    rules
  },
  plugins: [
    new WebpackObfuscator({
      rotateStringArray: true,
      stringArray: true,
      stringArrayEncoding: ['rc4'],
      stringArrayThreshold: 0.75
    }),
    new BytenodeWebpackPlugin({ compileForElectron: true })
  ],
  target: 'electron-main'
}

Support for `contextIsolation: true, nodeIntegration: false, sandbox: true`

  • The example for forge/webpack/ts turns on node integration for the renderer to make bytenode-webpack-plugin work
  • The readme states there might be other ways to make bytenode-webpack-plugin work
  • Can you provide a minimal example of such a solution that does not enable node integration?
  • Even pointers would be helpful, say I wanted; { contextIsolation: true, nodeIntegration: false, sandbox: true } (the electron default), what other methods could make bytenode work for preload and renderer?

Can I exclude some files?

Because of some known issues of bytenode, I need to exclude some files to be compiled into jsc, But there seems no option for this?

Webpack "Critical Dependency" issue

Hi,

I just started experimenting with this plugin, but when I run it I get

"Compiled with problems:X

WARNING in ./node_modules/bytenode/lib/index.js 369:52-75

Critical dependency: the request of a dependency is an expression

WARNING in ./node_modules/bytenode/lib/index.js 369:52-75

Critical dependency: the request of a dependency is an expression
"

Appearing on top of my electron window. Is there something obvious to fix here?

Folder names given .compiled instead of files

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch @herberttn/[email protected] for the project I'm working on.

/lib/plugin.js

To be more lazy in my forge config, I added a skip for web, since if nodeIntegration is enabled for a renderer, forge makes the target one of the electron- variants, whereas otherwise it's web. Forge's webpack plugin doesn't allow configuring different plugins for individual renderers, hence this takes advantage of that automatic target configuration by allowing everything to be passed in, only compiling the renderer that has nodeIntegration set to true.

/lib/utils.js

When nesting (multiple?) entry points the paths are resolved in a way that breaks the build; the folder name is given the .compiled extension instead of the file:

  • This: something/ui.compiled/index.jsc
  • Instead of: something/ui/index.compiled.jsc

Here is the diff that solved my problem:

diff --git a/node_modules/@herberttn/bytenode-webpack-plugin/lib/plugin.js b/node_modules/@herberttn/bytenode-webpack-plugin/lib/plugin.js
index c621dee..7acafbc 100644
--- a/node_modules/@herberttn/bytenode-webpack-plugin/lib/plugin.js
+++ b/node_modules/@herberttn/bytenode-webpack-plugin/lib/plugin.js
@@ -26,6 +26,16 @@ class BytenodeWebpackPlugin {
     apply(compiler) {
         const logger = compiler.getInfrastructureLogger(this.name);
         setupLifecycleLogging(compiler, this.name, this.options);
+        if (this.options.compileForElectron) {
+            const target = compiler.options.target;
+            if (target) {
+                const targets = Array.isArray(target) ? target : [target];
+                if (!targets.some((target) => target.startsWith('electron-'))) {
+                    logger.warn(`Not using bytenode because [${targets.join(', ')}] is marked as "compileForElectron: true" but has "target: 'web'".`);
+                    return;
+                }
+            }
+        }
         logger.debug('original webpack.options.entry', compiler.options.entry);
         const { entries: { ignored, loaders, targets }, modules } = prepare(compiler);
         logger.debug('prepared ignores', Object.fromEntries(ignored.entries()));
diff --git a/node_modules/@herberttn/bytenode-webpack-plugin/lib/utils.js b/node_modules/@herberttn/bytenode-webpack-plugin/lib/utils.js
index 79abcda..116ed0c 100644
--- a/node_modules/@herberttn/bytenode-webpack-plugin/lib/utils.js
+++ b/node_modules/@herberttn/bytenode-webpack-plugin/lib/utils.js
@@ -55,7 +55,12 @@ function fromCompiledToTargetExtension(file) {
 }
 exports.fromCompiledToTargetExtension = fromCompiledToTargetExtension;
 function fromTargetToCompiledExtension(file) {
-    return file.replace(TARGET_EXTENSION_REGEX, COMPILED_EXTENSION);
+    const dest = file.replace(TARGET_EXTENSION_REGEX, COMPILED_EXTENSION);
+    if (!dest.includes('.compiled.jsc')) {
+        const patchedDest = dest.replace('.compiled', '');
+        return patchedDest.replace('.jsc', '.compiled.jsc');
+    }
+    return dest;
 }
 exports.fromTargetToCompiledExtension = fromTargetToCompiledExtension;
 function isCompiledExtension(file) {

This issue body was partially generated by patch-package.

Add `vue-cli-electron-builder` support

Thank you for the very amazing lib, but i meet some problem when rederer

image

 error  in ./src/renderer/main.loader.js

Module build failed (from ./node_modules/thread-loader/dist/cjs.js):
Thread Loader (Worker 0)

yo guys, im using vue-cli-electron-builder lib, when i add your plugin to build it mind me module cannot be found

Compile a ES6 version to let it run on non-typescript environment

Hello, May I know whether it can compile a ES6 version to let this run on a environment without typescript support?
current version must have typescript support, otherwise it will error as follow:

`/Users/Cyrus/projectX/node_modules/@herberttn/bytenode-webpack-plugin/lib/index.js:65
const files = entryPoint?.getFiles() ?? [];
^

SyntaxError: Unexpected token .
at new Script (vm.js:83:7)
at NativeCompileCache._moduleCompile (/Users/Cyrus/projectX/node_modules/v8-compile-cache/v8-compile-cache.js:240:18)
at Module._compile (/Users/Cyrus/projectX/node_modules/v8-compile-cache/v8-compile-cache.js:184:36)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (/Users/Cyrus/projectX/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at Object. (/Users/Cyrus/projectX/webpack.app.config.js:4:31)
at Module._compile (/Users/Cyrus/projectX/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (/Users/Cyrus/projectX/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at Object. (/Users/Cyrus/projectX/bin/build.js:3:17)
at Module._compile (/Users/Cyrus/projectX/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (/Users/Cyrus/projectX/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at WEBPACK_OPTIONS (/Users/Cyrus/projectX/node_modules/webpack-cli/bin/utils/convert-argv.js:114:13)
at requireConfig (/Users/Cyrus/projectX/node_modules/webpack-cli/bin/utils/convert-argv.js:116:6)
at /Users/Cyrus/projectX/node_modules/webpack-cli/bin/utils/convert-argv.js:123:17
at Array.forEach ()
at module.exports (/Users/Cyrus/projectX/node_modules/webpack-cli/bin/utils/convert-argv.js:121:15)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: webpack --progress --profile --bail --mode production --config bin/build.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/Cyrus/.npm/_logs/2021-06-05T04_49_18_584Z-debug.log
The terminal process "/bin/zsh '-c', 'npm run build'" terminated with exit code: 1.`

Add `webpack v5` support

Hello, I am trying to package and use webpack5, but it is returning the following error:

[webpack-cli] TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object
    at new NodeError (node:internal/errors:363:5)
    at validateString (node:internal/validators:119:11)
    at Object.isAbsolute (node:path:403:5)
    at isDependency (C:\ProjetosSSD\SlayderGames\Launcher\Patcher\node_modules\@herberttn\bytenode-webpack-plugin\lib\index.js:241:28)
    at C:\ProjetosSSD\SlayderGames\Launcher\Patcher\node_modules\@herberttn\bytenode-webpack-plugin\lib\index.js:210:28
    at Array.map (<anonymous>)
    at prepare (C:\ProjetosSSD\SlayderGames\Launcher\Patcher\node_modules\@herberttn\bytenode-webpack-plugin\lib\index.js:209:37)
    at C:\ProjetosSSD\SlayderGames\Launcher\Patcher\node_modules\@herberttn\bytenode-webpack-plugin\lib\index.js:154:27
    at Array.map (<anonymous>)
    at BytenodeWebpackPlugin.preprocessEntry (C:\ProjetosSSD\SlayderGames\Launcher\Patcher\node_modules\@herberttn\bytenode-webpack-plugin\lib\index.js:153:24) {
  code: 'ERR_INVALID_ARG_TYPE'
}
const { merge } = require('webpack-merge')
const BytenodeWebpackPlugin = require('@herberttn/bytenode-webpack-plugin').BytenodeWebpackPlugin
const common = require('./webpack.common.js')

module.exports = merge(common, {
    mode: 'production',
    plugins: [new BytenodeWebpackPlugin()],
})

*Just putting a note, this plugin is sensational, congratulations to the developers.

Source code leak

Hello! It seems that version >=2.0.0 of this module, after adding support for webpack 5, includes the source code in the final build files.
I also tested the examples in this repository to exclude a possible issue with my configuration, and got the same results.
For reference I tested this example for webpack 4 and it worked just fine: https://github.com/spaceagetv/electron-bytenode-example

Lose require jsc in renderer entry file

Hi, thanks for your work. I am using this plugin with electron-builder.

It works fine in electron-main, but not renderer.

Specifically, this plugin can output both main and renderer jsc files and the entry file.

The entry file for main is ok, it contains the coderequire("./main.compiled.jsc").

But the renderer entry file does not contain the require code, but any other file, such as the css file import in js.

WHY?

In order to run, i add following code in index.html to load renderer's jsc file and it works fine:

if (process.env.NODE_ENV !== 'development') {
  require.extensions[".css"] = () => {
    return;
  };
  require('./main.compiled.jsc');
}

the browser code:

mainWindow = new BrowserWindow({
      show: false,
      width: 1024,
      height: 728,
      icon: getAssetPath('icon.png'),
      webPreferences: {
          nodeIntegration: true,
          nodeIntegrationInWorker: true,
          contextIsolation: false,
          devTools: true,
          preload: app.isPackaged
              ? path.join(__dirname, 'preload.js')
              : path.join(__dirname, '../../.erb/dll/preload.js'),
      },
  });

The renderer webpack config is similar to main's not special:

/**
 * Build config for electron renderer process
 */

import path from 'path';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import {BundleAnalyzerPlugin} from 'webpack-bundle-analyzer';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
import {merge} from 'webpack-merge';
import TerserPlugin from 'terser-webpack-plugin';
import {BytenodeWebpackPlugin} from '@herberttn/bytenode-webpack-plugin';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import checkNodeEnv from '../scripts/check-node-env';
import deleteSourceMaps from '../scripts/delete-source-maps';

checkNodeEnv('production');
deleteSourceMaps();

const configuration: webpack.Configuration = {
    devtool: 'source-map',

    mode: 'production',

    target: 'electron-renderer',

    entry: {
        main: path.join(webpackPaths.srcRendererPath, 'main.ts'),
    },

    output: {
        path: webpackPaths.distRendererPath,
        publicPath: './',
        filename: '[name].js',
        library: {
            type: 'umd',
        },
    },

    module: {
        rules: [
            {
                test: /\.s?(a|c|le)ss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            sourceMap: true,
                            importLoaders: 1,
                        },
                    },
                    'sass-loader',
                ],
                include: /\.module\.s?(c|a)ss$/,
            },
            {
                test: /\.s?(a|c|le)ss$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
                exclude: /\.module\.s?(c|a)ss$/,
            },
            // Fonts
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: 'asset/resource',
            },
            // Images
            {
                test: /\.(png|jpg|jpeg|gif)$/i,
                type: 'asset/resource',
            },
            // SVG
            {
                test: /\.svg$/,
                use: [
                    {
                        loader: '@svgr/webpack',
                        options: {
                            prettier: false,
                            svgo: false,
                            svgoConfig: {
                                plugins: [{removeViewBox: false}],
                            },
                            titleProp: true,
                            ref: true,
                        },
                    },
                    'file-loader',
                ],
            },
        ],
    },

    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                parallel: true,
            }),
            new CssMinimizerPlugin(),
        ],
    },

    plugins: [
        /**
         * Create global constants which can be configured at compile time.
         *
         * Useful for allowing different behaviour between development builds and
         * release builds
         *
         * NODE_ENV should be production so that modules do not perform certain
         * development checks
         */
        new webpack.EnvironmentPlugin({
            NODE_ENV: 'production',
            DEBUG_PROD: false,
        }),

        new MiniCssExtractPlugin({
            filename: 'style.css',
        }),

        new BundleAnalyzerPlugin({
            analyzerMode: process.env.ANALYZE === 'true' ? 'server' : 'disabled',
            analyzerPort: 8889,
        }),

        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: path.join(webpackPaths.srcRendererPath, 'index.ejs'),
            minify: {
                collapseWhitespace: true,
                removeAttributeQuotes: true,
                removeComments: true,
            },
            isBrowser: false,
            isDevelopment: process.env.NODE_ENV !== 'production',
        }),

        new webpack.DefinePlugin({
            'process.type': '"renderer"',
        }),
        new BytenodeWebpackPlugin({
            compileForElectron: true,
        }),
    ],
};

export default merge(baseConfig, configuration);

electron forge + multiple renders

Is it possible to use this plugin if I have an electron application with multiple renders?

I have 3 renderers with node target and one with nodeIntegration=false, this cannnot change.

Please advise! Thank you.

`electron-forge-typescript-webpack` example has runtime error

Simply calling npm run start on this example will cause this error to show up in the browser console:

Uncaught ReferenceError: require is not defined
    at Object.events (index.js:3651:1)
    at __webpack_require__ (index.js:3735:33)
    at fn (index.js:3923:21)
    at ./node_modules/webpack/hot/emitter.js (index.js:2999:20)
    at __webpack_require__ (index.js:3735:33)
    at fn (index.js:3923:21)
    at ./node_modules/webpack-dev-server/client/utils/reloadApp.js (index.js:2781:80)
    at __webpack_require__ (index.js:3735:33)
    at fn (index.js:3923:21)
    at ./node_modules/webpack-dev-server/client/index.js?protocol=ws%3A&hostname=0.0.0.0&port=3000&pathname=%2Fws&logging=info&overlay=true&reconnect=10&hot=true&live-reload=true (index.js:998:77)

"unable to load preload script" error when changing contextIsolation to true and nodeIntegration to false

I git cloned and started https://github.com/herberttn/bytenode-webpack-plugin/tree/main/examples/electron-forge-typescript-webpack

I tried to change the contextIsolation and the nodeIntegration settings respectively to true and false :

const createWindow = (): void => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
    webPreferences: {
      //contextIsolation: false,
      //nodeIntegration: true,
      //preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,

      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      nodeIntegration: false,
      contextIsolation: true,
      nodeIntegrationInWorker: false,
      nodeIntegrationInSubFrames: false,
      webviewTag: true,
      webSecurity: true

    },
  });

  // and load the index.html of the app.
  void mainWindow.loadURL(MAIN_WINDOW_WEBPACK_ENTRY);

with preload.ts :

console.log('💃 hello from preload')

// https://www.electronjs.org/docs/latest/tutorial/ipc


const {
  contextBridge,
  ipcRenderer,
  shell,
  webFrame
} = require("electron")



export {}
declare global {
  interface Window {
    api: {
      send: (channel: string, ...arg: any) => void;
      receive: (channel: string, func: (event: any, ...arg: any) => void) => void;
      electronIpcSendTo: (window_id: string, channel: string, ...arg: any) => void;
      electronIpcSend: (channel: string, ...arg: any) => void;
      giveMeAStream: (eventId: string) => void;
      electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => void;
      electronIpcSendSync: (channel: string, ...arg: any) => void;
      electronIpcInvoke: (channel: string, ...arg: any) => void;
      electronIpcPostMessage: (channel: string, message: any, transfer?: MessagePort[]) => void;
      electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) => void;
      electronIpcRemoveListener:  (channel: string, listener: (event: any, ...arg: any) => void) => void;
      electronIpcRemoveAllListeners: (channel: string) => void;

      setFullscreen: (flag: any) => void;

    };

    attachEvent(event: string, listener: EventListener): boolean;
    detachEvent(event: string, listener: EventListener): void;

    // https://www.electronjs.org/docs/latest/tutorial/context-isolation#usage-with-typescript

    bwScrollAPI: {
      getScrollAmount: () => void;
    }
  }
}


contextBridge.exposeInMainWorld(
  "api", {

      electronIpcPostMessage: (channel: string, message: any, transfer?: MessagePort[]) => {
        ipcRenderer.postMessage(channel, message, transfer)
      },
      send: (channel: any, data: any) => {
          console.log("preload-send called: args: ", data);
          ipcRenderer.invoke(channel, data).catch(e => console.log(e))
      },
      receive: (channel: any, func: any) => {
        console.log("preload-receive called. args: ");
        ipcRenderer.on(channel, (event, ...args) => func(...args));
      },

      electronIpcSendTo: (window_id: number, channel: string, ...arg: any) => {
        ipcRenderer.sendTo(window_id, channel, arg);
      },

      electronIpcSend: (channel: string, ...arg: any) => {
        ipcRenderer.send(channel, arg);
      },

      giveMeAStream: (eventId: string) => {
        ipcRenderer.send('give-me-a-stream', eventId)
      },

      electronIpcSendSync: (channel: string, ...arg: any) => {
        return ipcRenderer.sendSync(channel, arg);
      },
      // https://www.electronjs.org/docs/latest/api/ipc-renderer#ipcrendererinvokechannel-args
      electronIpcInvoke: (channel: string, ...arg: any) => {
        return ipcRenderer.invoke(channel, ...arg)
      },
      electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => {
        ipcRenderer.on(channel, listener);
      },
      electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) => {
        ipcRenderer.once(channel, listener);
      },
      electronIpcRemoveListener:  (channel: string, listener: (event: any, ...arg: any) => void) => {
        ipcRenderer.removeListener(channel, listener);
      },
      electronIpcRemoveAllListeners: (channel: string) => {
        ipcRenderer.removeAllListeners(channel);
      },

      setFullscreen: (flag: string) => {
        ipcRenderer.invoke('setFullscreen', flag);
      },

  },
)

But, after this change, I get this error: unable to load preload script

image

what am I missing ? How to make it work?

ChunkLoadError

when i use webpack and there are more than 1 chunck, it will report "ChunkLoadError". For Example, before compiling, there are two chunck A (index.js in the dir A) and B(index.js in the dir B), and there is "const a = require('A')" in index.js of B dir. after complied, it will report error "chunck load error,failed to load chunk A: A/index.js". Becase there is no A/index.js, only A/index.jsc

use electron directly, got "Cannot find module 'node:assert/strict'"

I use this plugin first, webpack.config.js is just like your example, but I don't use electron-forge.

// src/main.js
const { app, BrowserWindow } = require('electron');
/** createWindow and so on **/
// webpack.electron.config.js
module.exports = {
  entry: {
    main: join(__dirname, 'src/main.js'),
  },
  output: {
    filename: '[name].js',
    devtoolModuleFilenameTemplate: '[absolute-resource-path]',
    // libraryTarget: 'commonjs2',
  },
  resolve: {
    extensions: ['.js', '.json'],
  },
  plugins: [
    new BytenodeWebpackPlugin({
      compileAsModule: true,
      compileForElectron: true,
    }),
  ],
  mode: 'production',
  target: 'electron-main',
}
// shell
webpack ./webpack.electron.config.js
/** got Error: Cannot find module 'node:assert/strict' **/

even if I use bytenode directly, there are similar errors.

here is my reproducible code: https://github.com/forever-z-133/bytenode-electron-error-example

please help me, if you have time, Thank you very much.

Windows Electron bug?

We're seeing an error in the electron-bytenode-example project when launching on Windows:
spaceagetv/electron-bytenode-example#31

Haven't quite narrowed this issue down yet, but I'm guessing that it's a bytenode-webpack-plugin issue… and probably something related to the Windows-specific code in loaders.ts. If it's a loader issue, it's probably not specific to Electron.

`electron forge make` yields both a compiled file and a "plain text" file. If the plain text file is removed, the executable does not work anymore

Example taken from here: https://github.com/herberttn/bytenode-webpack-plugin/tree/main/examples/electron-forge-typescript-webpack

electron forge make yields both a compiled file and a "plain text" file:

raphy@raohy:~/electron-forge-typescript-webpack/out/electron-forge-typescript-webpack-example-linux-x64/resources/app/.webpack/main$ ls -lah
total 44K
drwxrwxr-x 3 raphy raphy 4,0K ago 31 18:02 .
drwxrwxr-x 4 raphy raphy 4,0K ago 31 18:02 ..
-rw-rw-r-- 1 raphy raphy  23K ago 31 18:02 index.compiled.jsc
-rw-rw-r-- 1 raphy raphy 5,6K ago 31 18:02 index.js
drwxrwxr-x 2 raphy raphy 4,0K ago 31 18:02 native_modules

Once I remove the plain text file:

raphy@raohy:~/electron-forge-typescript-webpack/out/electron-forge-typescript-webpack-example-linux-x64/resources/app/.webpack/main$ rm index.js 

the executable does not work anymore :

raphy@raohy:~/electron-forge-typescript-webpack$ ./out/electron-forge-typescript-webpack-example-linux-x64/electron-forge-typescript-webpack-example 
[18682:0831/180643.305136:ERROR:node_bindings.cc(267)] Most NODE_OPTIONs are not supported in packaged apps. See documentation for more details.
A JavaScript error occurred in the main process
Uncaught Exception:
Error: Cannot find module '/home/raphy/electron-forge-typescript-webpack/out/electron-forge-typescript-webpack-example-linux-x64/resources/app/.webpack/main'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1002:15)
    at n._resolveFilename (node:electron/js2c/browser_init:2:109797)
    at node:electron/js2c/browser_init:2:115663
    at node:electron/js2c/browser_init:2:115906
    at node:electron/js2c/browser_init:2:115910
    at BuiltinModule.compileForInternalLoader (node:internal/bootstrap/loaders:331:7)
    at BuiltinModule.compileForPublicLoader (node:internal/bootstrap/loaders:269:10)
    at loadBuiltinModule (node:internal/modules/cjs/helpers:50:9)
    at Module._load (node:internal/modules/cjs/loader:862:15)
    at f._load (node:electron/js2c/asar_bundle:2:13330)
[18714:0831/180643.608410:ERROR:gpu_memory_buffer_support_x11.cc(49)] dri3 extension not supported.

So... may be I'm missing something...

because I do not understand the benefit and usefulness of producing a JS BInary, if without the plain text file, which is supposed to be removed if we want to hide the plain JS code, the executable does not work

webpack 5 integration doesn't work - "SyntaxError: Invalid or unexpected token"

Error:

/Development/electron-app/out/main/main.compiled.jsc:1
M��q|s�/�
 ^

SyntaxError: Invalid or unexpected token

My apps only output file is ./src/main/index.ts -> ./out/main/main.js

The webpack output code of main.js is below

(() => {
var exports = {};
exports.id = "main";
exports.ids = ["main"];
exports.modules = {

/***/ "./node_modules/@herberttn/bytenode-webpack-plugin/lib/loaders.js?{\"imports\":[\"./src/main/index.ts\"]}!":
/*!*************************************************************************************************************!*\
  !*** ./node_modules/@herberttn/bytenode-webpack-plugin/lib/loaders.js?{"imports":["./src/main/index.ts"]}! ***!
  \*************************************************************************************************************/
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {

__webpack_require__(/*! bytenode */ "bytenode");
__webpack_require__(/*! ./src/main/index.ts */ "./src/main/index.ts");

/***/ }),

/***/ "bytenode":
/*!***************************!*\
  !*** external "bytenode" ***!
  \***************************/
/***/ ((module) => {

"use strict";
module.exports = require("bytenode");;

/***/ })

};
;

// load runtime
var __webpack_require__ = require("./main.compiled.jsc");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = (__webpack_exec__("./node_modules/@herberttn/bytenode-webpack-plugin/lib/loaders.js?{\"imports\":[\"./src/main/index.ts\"]}!"));
var __webpack_export_target__ = exports;
for(var i in __webpack_exports__) __webpack_export_target__[i] = __webpack_exports__[i];
if(__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });

})();

It's barfing at this line: var __webpack_require__ = require("./main.compiled.jsc");

If I set the file content of main.js to just be below, it all works perfectly.

require("bytenode"); 
require("./main.compiled.jsc");

I've been trying to debug how the content is created, but it seems to be failing due to this logic:

async function updateLoaderToRequireCompiledAssets(compilation: Compilation, name: string, asset: Source, files: string[]): Promise<void> {
logger.debug('updating loader to require compiled assets');
const source = await replaceSource(asset, raw => {
for (const file of files) {
raw = raw.replace(file, fromTargetToCompiledExtension(file));
}
return raw;
});
compilation.updateAsset(name, source);
}

I see that it's simple a string replacement of main.compiled.js -> main.compiled.jsc. This doesn't work because bytenode hasn't been loaded yet.

That's about as far into debugging it that I've gotten thus far. It'd be great if we could match the entire __webpack_require__ line, but I don't know if file can ever be a filepath as opposed to just a name

Wrong path to ".jsc" in sub_window

i have a screenplay folder and that has a renderer, preload and many assets. All works normally!
After adding your plugin, my code break all.

After 15 minutes of researching, i find out:
Error in console: "Uncaught Error: Cannot find module './sub_window.compiled.jsc'"
Cause by:
My index.html has included sub_window.js, in subwindow.js include "./sub_window.compiled.jsc", but actually it must be "../sub_window.compiled.jsc" because it is included in sub_window/index.html

Right now i have to modified my code after run built. Just adding a DOT in a file :D

Screenshot 2023-03-03 104845

Preloader - Running into Compilation Error

I am trying to use the library. I was trying to use your library with the example electron-forge-typescript-webpack as a template.

However, I am running into an issue with the following:

An unhandled rejection has occurred inside Forge:
Error: Compilation errors in the preload: group_0:
  assets by info 2.98 KiB [immutable]
    assets by path *.json 150 bytes
      asset main_window_compiled.783c92c0224cb1109eb5.hot-update.json 44 bytes [emitted] [immutable] [hmr]
      asset preload_compiled.783c92c0224cb1109eb5.hot-update.json 40 bytes [emitted] [immutable] [hmr]
      + 2 assets
    assets by path *.jsc 2.25 KiB
      asset main_window.compiled.783c92c0224cb1109eb5.hot-update.jsc 1.13 KiB [emitted] [immutable] [hmr] (name: main_window.compiled)
      asset preload.compiled.783c92c0224cb1109eb5.hot-update.jsc 1.13 KiB [emitted] [immutable] [hmr] (name: preload.compiled)
    assets by path *.js 598 bytes
      asset main_window.783c92c0224cb1109eb5.hot-update.js 301 bytes [emitted] [immutable] [hmr] (name: main_window)
      asset preload.783c92c0224cb1109eb5.hot-update.js 297 bytes [emitted] [immutable] [hmr] (name: preload)
  asset main_window/preload.js 254 KiB [emitted] (name: main_window)
  asset preload/preload.js 254 KiB [emitted] (name: preload)
  asset main_window.compiled/preload.jsc 227 KiB [emitted] (name: main_window.compiled)
  asset preload.compiled/preload.jsc 227 KiB [emitted] (name: preload.compiled)
  Entrypoint preload 255 KiB = preload/preload.js 254 KiB preload.783c92c0224cb1109eb5.hot-update.js 297 bytes
  Entrypoint main_window 255 KiB = main_window/preload.js 254 KiB main_window.783c92c0224cb1109eb5.hot-update.js 301 bytes
  Entrypoint preload.compiled 228 KiB = preload.compiled/preload.jsc 227 KiB preload.compiled.783c92c0224cb1109eb5.hot-update.jsc 1.13 KiB
  Entrypoint main_window.compiled 228 KiB = main_window.compiled/preload.jsc 227 KiB main_window.compiled.783c92c0224cb1109eb5.hot-update.jsc 1.13 KiB
  runtime modules 106 KiB 50 modules
  cached modules 175 KiB [cached] 32 modules
  javascript modules 312 bytes
    node:assert/strict 39 bytes [built] [1 error]
    node:child_process 39 bytes [built] [1 error]
    node:fs 39 bytes [built] [1 error]
    node:module 39 bytes [built] [1 error]
    node:path 39 bytes [built] [1 error]
    node:vm 39 bytes [built] [1 error]
    node:v8 39 bytes [built] [1 error]
    node:zlib 39 bytes [built] [1 error]

  ERROR in node:assert/strict
  Module build failed: UnhandledSchemeError: Reading from "node:assert/strict" is not handled by plugins (Unhandled scheme).
  Webpack supports "data:" and "file:" URIs by default.
  You may need an additional plugin to handle "node:" URIs.
      at /home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/NormalModule.js:918:25
      at Hook.eval [as callAsync] (eval at create (/home/dallas/Github/mosaic/canvas-desktop/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
      at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/home/dallas/Github/mosaic/canvas-desktop/node_modules/tapable/lib/Hook.js:18:14)
      at Object.processResource (/home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/NormalModule.js:915:8)
      at processResource (/home/dallas/Github/mosaic/canvas-desktop/node_modules/loader-runner/lib/LoaderRunner.js:220:11)
      at iteratePitchingLoaders (/home/dallas/Github/mosaic/canvas-desktop/node_modules/loader-runner/lib/LoaderRunner.js:171:10)
      at runLoaders (/home/dallas/Github/mosaic/canvas-desktop/node_modules/loader-runner/lib/LoaderRunner.js:398:2)
      at NormalModule._doBuild (/home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/NormalModule.js:905:3)
      at NormalModule.build (/home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/NormalModule.js:1079:15)
      at /home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/Compilation.js:1374:12
      at NormalModule.needBuild (/home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/NormalModule.js:1408:26)
      at Compilation._buildModule (/home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/Compilation.js:1355:10)
      at /home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/util/AsyncQueue.js:305:10
      at Hook.eval [as callAsync] (eval at create (/home/dallas/Github/mosaic/canvas-desktop/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
      at AsyncQueue._startProcessing (/home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/util/AsyncQueue.js:295:26)
      at AsyncQueue._ensureProcessing (/home/dallas/Github/mosaic/canvas-desktop/node_modules/webpack/lib/util/AsyncQueue.js:282:12)
   @ ./node_modules/bytenode/lib/index.js 3:15-44
   @ ./src/main/preloaders/preload.loader.js 1:0-19

Is this something to do with my preloader? I cant find much on the error.

Add `electron-builder` support

Hi there, you've done an incredible and exciting job on electron-forge!
However, as we can see there're tons of projects built within electron-builder.
So are there any plans for electron-builder supporting?
Really appreciated!

error on brand new electron app generated with electron-forge

hi, I generate an electron application using create-electron-app with electron-forge v6.61 beta channel and when I am trying to run yarn package it gives me:

An unhandled error has occurred inside Forge:
The "path" argument must be of type string. Received an instance of Object
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object
    at validateString (internal/validators.js:124:11)
    at Object.isAbsolute (path.js:353:5)
    at isDependency (F:\git\electron-test-app\node_modules\@herberttn\bytenode-webpack-plugin\src\index.ts:317:14)
    at F:\git\electron-test-app\node_modules\@herberttn\bytenode-webpack-plugin\src\index.ts:276:24
    at Array.map (<anonymous>)
    at prepare (F:\git\electron-test-app\node_modules\@herberttn\bytenode-webpack-plugin\src\index.ts:275:35)
    at F:\git\electron-test-app\node_modules\@herberttn\bytenode-webpack-plugin\src\index.ts:206:21
    at Array.map (<anonymous>)
    at BytenodeWebpackPlugin.preprocessEntry (F:\git\electron-test-app\node_modules\@herberttn\bytenode-webpack-plugin\src\index.ts:205:20)
    at BytenodeWebpackPlugin.processOptions (F:\git\electron-test-app\node_modules\@herberttn\bytenode-webpack-plugin\src\index.ts:135:52)
    at BytenodeWebpackPlugin.apply (F:\git\electron-test-app\node_modules\@herberttn\bytenode-webpack-plugin\src\index.ts:47:77)
    at createCompiler (F:\git\electron-test-app\node_modules\webpack\lib\webpack.js:74:12)
    at create (F:\git\electron-test-app\node_modules\webpack\lib\webpack.js:127:16)
    at webpack (F:\git\electron-test-app\node_modules\webpack\lib\webpack.js:151:32)
    at f (F:\git\electron-test-app\node_modules\webpack\lib\index.js:55:16)
    at F:\git\electron-test-app\node_modules\@electron-forge\plugin-webpack\src\WebpackPlugin.ts:111:5
error Command failed with exit code 1.

what is wrong?

Unexpected token 'export' Electronjs ByteNode

I meet a very new error:

SyntaxError: Unexpected token 'export'
at new Script (node:vm:100:7)
at Object.compileCode (C:\GitHub... (remove) ...\node_modules\bytenode\lib\index.js:28:18)

It is still working but error throw to terminal while i am building production.

my Typescript config like this:

"module": "CommonJS",
"target": "es2022"

NodeJS 12 Support ?

Hello !

I am looking to use your webpack plugin, but unfortunately I get errors when I load the module on my webpack config JS file.
For technical reasons, I can't go further Electron 11 so NodeJS 12 is the last version I can use. I am also forced to stay on Webpack 4.

I tried to use version 1.2.5, without success : it seems like it also require NodeJS 14.

Is there anything I can do to use it ? Upgrading my Electron stack is really not an option.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.