检测电子中节点环境的方法

时间:2019-05-08 07:32:49

标签: node.js npm webpack electron webpack-dev-server

我想知道如何检测电子主文件中的NODE_ENV变量。

我要尝试将loadURL的{​​{1}}设置为localhost:8080,否则将NODE_ENV === 'dev'设置为/dist/index.html。因为我想在开发过程中使用一些webpack-dev-server功能,例如HMR和实时重载。

我以这种方式设置了我的npm脚本,但是我不确定它是否正确。

package.json

  "scripts": {
    "start": "electron .",
    "start:dev": "NODE_ENV=dev webpack-dev-server --config webpack.dev.js && electron .",
    "build": "NODE_ENV=prod webpack --config webpack.prod.js && electron ."
  },

这是我的电子主文件。

main.js

const electron = require('electron');
const url = require('url');
const path = require('path');

const { app, BrowserWindow } = electron;

let mainWindow = null;

app.on('ready', function() {   // eslint-disable-line 
  mainWindow = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
    },
  });

  // mainWindow.loadURL('http://localhost:8080/');

  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, '/dist/index.html'),
    protocol: 'file:',
    slashes: true,
  }));

  mainWindow.on('closed', function(){  
    app.quit();
  });
});

2 个答案:

答案 0 :(得分:0)

嗯,一些快速的解决方案是if语句

if(process.env.NODE_ENV === 'dev') {
  mainWindow.loadURL('http://localhost:8080/')
} else {
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, '/dist/index.html'),
    protocol: 'file:',
    slashes: true,
  }));
}

答案 1 :(得分:0)

我将分享我正在处理的一个项目中的一些代码,希望该代码有助于阐明您如何能够解决您的问题。 如果在将应用程序打包为electron-builderelectron-packager之后未从可执行文件加载应用程序,Electron认为环境始终是“开发中”。 Distinguishing "development" from "production" #7714

这使我不得不花费大量时间来测试其他在产品与开发中表现不同的项目,但是至少这似乎可以持续工作。

了解后,您可以使用electron.app.isPackaged在main.js文件中设置一个变量,该变量可用于控制某些功能。

下面的演示...如果您有混淆,代码的注释部分中没有说明,请与我联系。

这是我在运行Electron v7.0.1的项目中使用的npm脚本:

"main": "main.js",
  "scripts": {
    "test": "jest",
    "prod": "webpack --mode production --config webpack.build.config.js && electron --noDevServer .",
    "start": "webpack-dev-server --hot --host 0.0.0.0 --config=./webpack.dev.config.js --mode development",
    "build": "webpack --config webpack.build.config.js --mode production",
    "package-mac": "electron-builder  build --x64 --mac",
    "package-all": "electron-builder  build -mwl",
    "package-linux": "electron-builder build --linux",
    "gh-publish-mac": "electron-builder build --x64 --mac -p always",
    "gh-publish": "electron-builder build -mwl -p always",
    }

这是main.js文件中的代码,用于基于dev vs prod管理某些功能:

// Keep a reference for dev mode
let dev = false;

// this works if npm run build, followed by npm run package-(any of the scripts),
// and then open from executable file
dev = !app.isPackaged;

function createWindow() {
  // Create the new browser window instance. devtools set to false in production
  if (!dev) {
    mainWindow = new BrowserWindow({
      width: 2000,
      height: 1000,
      minWidth: 1304,
      minHeight: 700,
      backgroundColor: "-webkit-linear-gradient(top, #3dadc2 0%,#2f4858 100%)",
      show: false,
      title: "Swell",
      allowRunningInsecureContent: true,
      webPreferences: {
        devTools: false,
        nodeIntegration: true,
        sandbox: false,
        webSecurity: true,
      },
      icon: `${__dirname}/src/assets/icons/64x64.png`,
    });
  } else {
    mainWindow = new BrowserWindow({
      width: 2000,
      height: 1000,
      minWidth: 1304,
      minHeight: 700,
      backgroundColor: "-webkit-linear-gradient(top, #3dadc2 0%,#2f4858 100%)",
      show: false,
      title: "Swell",
      allowRunningInsecureContent: true,
      webPreferences: {
        nodeIntegration: true,
        sandbox: false,
        webSecurity: true,
      },
      icon: `${__dirname}/src/assets/icons/64x64.png`,
    });
  }

  if (dev) {
    const {
      default: installExtension,
      REACT_DEVELOPER_TOOLS,
      REDUX_DEVTOOLS,
    } = require("electron-devtools-installer");
    // If we are in developer mode Add React & Redux DevTools to Electon App
    installExtension(REACT_DEVELOPER_TOOLS)
      .then((name) => console.log(`Added Extension:  ${name}`))
      .catch((err) => console.log("An error occurred: ", err));

    installExtension(REDUX_DEVTOOLS)
      .then((name) => console.log(`Added Extension:  ${name}`))
      .catch((err) => console.log("An error occurred: ", err));
  }

  // and load the index.html of the app.
  let indexPath;

  if (dev && process.argv.indexOf("--noDevServer") === -1) {
    // if we are in dev mode load up 'http://localhost:8080/index.html'
    indexPath = url.format({
      protocol: "http:",
      host: "localhost:8080",
      pathname: "index.html",
      slashes: true,
    });
  } else {
    indexPath = url.format({
      // if we are not in dev mode load production build file
      protocol: "file:",
      pathname: path.join(__dirname, "dist", "index.html"),
      slashes: true,
    });
  }

  // our new app window will load content depending on the boolean value of the dev variable
  mainWindow.loadURL(indexPath);

  // give our new window the earlier created touchbar
  mainWindow.setTouchBar(touchBar);

  // prevent webpack-dev-server from setting new title
  mainWindow.on("page-title-updated", (e) => e.preventDefault());

  // Don't show until we are ready and loaded
  mainWindow.once("ready-to-show", () => {
    mainWindow.show();

    // Open the DevTools automatically if developing
    if (dev) {
      mainWindow.webContents.openDevTools();
    }
  });

  // Emitted when the window is closed.
  mainWindow.on("closed", () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.

    //tldr: Remove the BrowserWindow instance that we created earlier by setting its value to null when we exit Swell
    mainWindow = null;
  });

  //require menu file
  require("./menu/mainMenu");
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", () => {
  // createLoadingScreen();
  createWindow();
  if (!dev) {
    autoUpdater.checkForUpdates();
  }
});

ipcMain.on("check-for-update", () => {
  //listens to ipcRenderer in UpdatePopUpContainer.jsx
  if (!dev) autoUpdater.checkForUpdates();
});