Как мне заставить веб-пакет работать с электроном с помощью aurelia? - PullRequest
0 голосов
/ 08 февраля 2020

прямо сейчас я просто пытаюсь добавить электрон к основному приложению c hello world (ну, я настроил некоторые параметры в aurelia cli, но все же это просто в hello world webpack + typcript).

Моя текущая попытка - использовать webpack-Electron , что я получаю, это белый экран смерти. Я также могу получить черный экран смерти, если я исключу рендерер, он не может найти ни один из файлов ресурсов в этом случае, он ищет их по неправильному пути.

вот мой src/main/app.ts

import { app, BrowserWindow } from "electron";
import * as path from "path";

let mainWindow: Electron.BrowserWindow;

const isDevelopment = process.env.NODE_ENV !== 'production';

function createWindowUrl(url) {
  const prefix = isDevelopment
    ? `http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}`
    : `file://${__dirname}`;

  return `${prefix}/${url}`;
}

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
    webPreferences: {
      nodeIntegration: true,
    }
  });


  // and load the index.html of the app.
  mainWindow.loadURL(createWindowUrl('../index.html'));

  // Open the DevTools.
  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.
    mainWindow = null;
  });
}

// 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", createWindow);

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On OS X 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();
  }
});

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

и мой src/renderer/main.ts, который, я уверен, неверен для https://medium.com/kendraio/using-angular-with-electron-webpack-b9763903823c

import {} from "../main"

Мне все равно, если я использую webpack-electron, но как мне заставить Аурелию работать с электроном таким образом, чтобы он также сохранял обычный код веб-сайта / сервера?

версий, но я сомневаюсь, что они имеют значение

Calebs-MBP:warmaster calebcushing$ yarn list --depth=0 --pattern "^webpack|^aurelia|^electron"
yarn list v1.21.1
├─ aurelia-animator-css@1.0.4
├─ aurelia-binding@2.5.2
├─ aurelia-bootstrapper@2.3.3
├─ aurelia-cli@1.2.3
├─ aurelia-dependency-injection@1.5.2
├─ aurelia-event-aggregator@1.0.3
├─ aurelia-framework@1.3.1
├─ aurelia-history-browser@1.4.0
├─ aurelia-history@1.2.1
├─ aurelia-hot-module-reload@0.2.1
├─ aurelia-loader-default@1.2.1
├─ aurelia-loader-webpack@2.2.1
├─ aurelia-loader@1.0.2
├─ aurelia-logging-console@1.1.1
├─ aurelia-logging@1.5.2
├─ aurelia-metadata@1.0.6
├─ aurelia-pal-browser@1.8.1
├─ aurelia-pal@1.8.2
├─ aurelia-path@1.1.5
├─ aurelia-polyfills@1.3.4
├─ aurelia-route-recognizer@1.3.2
├─ aurelia-router@1.7.1
├─ aurelia-task-queue@1.3.3
├─ aurelia-templating-binding@1.5.3
├─ aurelia-templating-resources@1.13.0
├─ aurelia-templating-router@1.4.0
├─ aurelia-templating@1.10.3
├─ aurelia-testing@1.0.0
├─ aurelia-tools@2.0.0
├─ aurelia-webpack-plugin@3.0.0
├─ electron-builder@22.3.2
├─ electron-devtools-installer@2.2.4
├─ electron-publish@22.3.2
├─ electron-to-chromium@1.3.345
├─ electron-webpack-js@2.3.4
├─ electron-webpack@2.7.4
├─ electron@8.0.0
├─ webpack-bundle-analyzer@3.6.0
├─ webpack-cli@3.3.10
├─ webpack-dev-middleware@3.7.2
├─ webpack-dev-server@3.10.3
├─ webpack-log@2.0.0
├─ webpack-merge@4.2.2
├─ webpack-sources@1.4.3
└─ webpack@4.41.5
✨  Done in 1.03s.

Ответы [ 2 ]

2 голосов
/ 09 февраля 2020

Так что это, вероятно, далеко не все, но я получил привет, чтобы отобразить в электронном виде, вот что я сделал

TL; DR; измените webpack.config.js baseUrl на '' (пустая строка)

добавьте их к package.json с вашим менеджером пакетов (я не уверен, требуется ли electron-builder)

    "electron": "^8.0.0",
    "electron-builder": "^22.3.2",
    "electron-webpack": "^2.7.4",
...scripts
    "build:electron": "npm run build && electron-webpack app",
    "package:electron": "npm run build:electron && electron-builder",
    "start:electron": "npm run build:dev && electron-webpack dev",
...// electron webpack and builder configuration
  "electronWebpack": {
    "commonSourceDirectory": "dist",
    "staticSourceDirectory": "static",
    "title": true
  },
  "build": {
    "directories": {
      "buildResources": "dist",
      "output": "electron"
    },
    "files": [ // actually include the dist folder
      {
        "from": "dist",
        "to": "dist"
      }
    ]
  },
  "main": "main.js",

затем добавьте src/main/app.ts и src/main/renderer.ts (средство визуализации останется пустым файлом)

в src/main/app.ts добавьте этот код, который в основном представляет собой код быстрого запуска машинописного текста с одним изменением. Файл, загруженный просто ../index.html, __dirname будет выглядеть не в том месте.

import { app, BrowserWindow } from "electron";
import * as path from "path";
import { format as formatUrl } from 'url';


let mainWindow: Electron.BrowserWindow;

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
  });
  const isDevelopment = process.env.NODE_ENV !== 'production';

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // and load the index.html of the app.
// this conditional is silly, but was the only way I figured out how to have it work in both dev and actually packaging the app
  if (isDevelopment) {
    mainWindow.loadFile(path.relative(__dirname, 'dist/index.html'))
  } else {
    mainWindow.loadURL(formatUrl({
      pathname: path.join(__dirname, 'dist/index.html'),
      protocol: 'file',
      slashes: true
    }));
  }

  // 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.
    mainWindow = null;
  });
}

// 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", createWindow);

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On OS X 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();
  }
});

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.

, а затем изменит webpack.config.js, как указано ранее, и попробуйте npm run start и npm run start:electron, и оба должны теперь бежать.

1 голос
/ 10 февраля 2020

с использованием Конденсатор для этого намного проще, просто следуйте этому документу .

Затем добавьте electron-builder как dev к проекту electron, добавленному конденсатором , Добавьте эти сценарии для упаковки вашего приложения, и вы готовы к go.

{
  "scripts": {
    "pack": "electron-builder --dir",
    "dist": "electron-builder"
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...