question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to load preload script in packaged app(same in DEBUG_PROD=true yarn build && yarn start)

See original GitHub issue

Prerequisites

  • [✅] Using yarn - v1.17.3
  • [✅ ] Using node 10.x - v10.16.0
  • [ ✅] Using an up-to-date master branch
  • [✅ ] Using latest version of devtools. See wiki for howto update
  • [ ✅] Link to stacktrace in a Gist (for bugs)

(anonymous) @ init.ts:204
./lib/renderer/init.ts @ init.ts:215
__webpack_require__ @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ bootstrap:83
NativeModule.compile @ internal/bootstrap/loaders.js:302
NativeModule.compileForPublicLoader @ internal/bootstrap/loaders.js:219
loadNativeModule @ internal/modules/cjs/helpers.js:23
Module._load @ internal/modules/cjs/loader.js:630
Module._load @ electron/js2c/asar.js:717
Module._load @ electron/js2c/asar.js:717
Module.runMain @ internal/modules/cjs/loader.js:944
(anonymous) @ internal/main/run_main_module.js:17
init.ts:205 Error: Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.
  • For issue in production release, devtools output of DEBUG_PROD=true yarn build && yarn start
  • [ ✅] Tried solutions mentioned in #400

Expected Behavior

No error.

Current Behavior

Error in console. Error info:

init.ts:204 Unable to load preload script: /Applications/希沃视频展台.app/Contents/Resources/app.asar/dist/renderer.prod.js

screenshot: image

Possible Solution

Context

I want to develop a webRTC app base on ERB. I add less-loader for less processing and some webRTC code for the video streaming. Then I encounter this error. If you need any further information, please let me know and I will append it as soon as possible.

main.dev.ts
/* eslint global-require: off, no-console: off */

/**
 * This module executes inside of electron's main process. You can start
 * electron renderer process from here and communicate with the other processes
 * through IPC.
 *
 * When running `yarn build` or `yarn build-main`, this file is compiled to
 * `./app/main.prod.js` using webpack. This gives us some performance wins.
 */
import path from 'path';
import { app, BrowserWindow, protocol } from 'electron';
import { autoUpdater } from 'electron-updater';
import log from 'electron-log';
import MenuBuilder from './menu';

export default class AppUpdater {
  constructor() {
    log.transports.file.level = 'info';
    autoUpdater.logger = log;
    autoUpdater.checkForUpdatesAndNotify();
  }
}

let mainWindow: BrowserWindow | null = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support');
  sourceMapSupport.install();
}

if (
  process.env.NODE_ENV === 'development' ||
  process.env.DEBUG_PROD === 'true'
) {
  require('electron-debug')();
}

const installExtensions = async () => {
  const installer = require('electron-devtools-installer');
  const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
  const extensions = ['REACT_DEVELOPER_TOOLS', 'REDUX_DEVTOOLS'];

  return Promise.all(
    extensions.map(name => installer.default(installer[name], forceDownload))
  ).catch(console.log);
};

const createWindow = async () => {
  if (
    process.env.NODE_ENV === 'development' ||
    process.env.DEBUG_PROD === 'true'
  ) {
    await installExtensions();
  }

  mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    fullscreen: true,
    webPreferences:
      process.env.NODE_ENV === 'development' || process.env.E2E_BUILD === 'true'
        ? {
            nodeIntegration: true
          }
        : {
            preload: path.join(__dirname, 'dist/renderer.prod.js')
          }
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  // @TODO: Use 'ready-to-show' event
  //        https://github.com/electron/electron/blob/master/docs/api/browser-window.md#using-ready-to-show-event
  mainWindow.webContents.on('did-finish-load', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    if (process.env.START_MINIMIZED) {
      mainWindow.minimize();
    } else {
      mainWindow.show();
      mainWindow.focus();
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  const menuBuilder = new MenuBuilder(mainWindow);
  menuBuilder.buildMenu();

  // Remove this if your app does not use auto updates
  // eslint-disable-next-line
  new AppUpdater();
};

const handleReady = async () => {
  await createWindow();
};

/**
 * Add event listeners...
 */

app.on('window-all-closed', () => {
  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('ready', handleReady);

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) createWindow();
});

// webpack.config.base.js
/**
 * Base webpack config used across other specific configs
 */

import path from 'path';
import webpack from 'webpack';
import { dependencies as externals } from '../app/package.json';

export default {
  externals: [...Object.keys(externals || {})],

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true,
            plugins: [
              [
                'import',
                {
                  libraryName: 'antd',
                  style: true
                }
              ]
            ]
          }
        }
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader'
          },
          {
            loader: 'less-loader',
            options: {
              javascriptEnabled: true
            }
          }
        ]
      }
    ]
  },

  output: {
    path: path.join(__dirname, '..', 'app'),
    // https://github.com/webpack/webpack/issues/1114
    libraryTarget: 'commonjs2'
  },

  /**
   * Determine the array of extensions that should be used to resolve modules.
   */
  resolve: {
    extensions: ['.js', '.jsx', '.json', '.ts', '.tsx'],
    modules: [path.join(__dirname, '..', 'app'), 'node_modules']
  },

  plugins: [
    new webpack.EnvironmentPlugin({
      NODE_ENV: 'production'
    }),

    new webpack.NamedModulesPlugin()
  ]
};

Your Environment

  • Node version : Node 10.16
  • Version or Branch used: master branch
  • Operating System and version : :OS X 10.15.3

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

24reactions
1henriq1commented, Apr 7, 2020

Here we solved this by changing this code:

mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    fullscreen: true,
    webPreferences:
      process.env.NODE_ENV === 'development' || process.env.E2E_BUILD === 'true'
        ? {
            nodeIntegration: true
          }
        : {
            preload: path.join(__dirname, 'dist/renderer.prod.js')
          }
  });

to this:

mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    fullscreen: true,
    webPreferences: {
      nodeIntegration: true
    }
  });
5reactions
saifeiLeecommented, Apr 7, 2020

Here we solved this by changing this code:

mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    fullscreen: true,
    webPreferences:
      process.env.NODE_ENV === 'development' || process.env.E2E_BUILD === 'true'
        ? {
            nodeIntegration: true
          }
        : {
            preload: path.join(__dirname, 'dist/renderer.prod.js')
          }
  });

to this:

mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    fullscreen: true,
    webPreferences: {
      nodeIntegration: true
    }
  });

Awesome! Thank you so much! It bothered me the whole day.

Read more comments on GitHub >

github_iconTop Results From Across the Web

electron-builder with browserWindow and preload.js. Unable ...
Unable to load preload script, but actually something was wrong with the initialize.js. in my file, has an error that remote.
Read more >
Context Isolation - Electron
Context Isolation is a feature that ensures that both your preload scripts and Electron's internal logic run in a separate context to the...
Read more >
A gluten-free Electron React setup [ft. live reload]
Create a new folder under electron-app and yarn init a package there. ... We told electron to load a preload script, but we...
Read more >
Old React App Not Starting | Solution | Yarn Start Error
Open terminal Install node modules, packages or React project dependencies Yarn was used as a package manager for this app command to ...
Read more >
Getting Started w/ Electron #3 - Preload Scripts - YouTube
Todays video will cover how to setup preload scripts and enable secure context Isolation inside your electron app. Using preload scripts ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found