Настройка приложения create-реакции с использованием электронного модуля
Я создал приложение реакции, используя create-react-app
подход, и я должен был сделать некоторые изменения в конфигурации веб-пакета, поэтому у меня есть ejected
мое приложение реагировать тоже. Он отлично работает на локальном хосте в браузере. Теперь я пытаюсь инкапсулировать свое приложение, используя электрон, чтобы лучше выглядеть и чувствовать. я использую main.js
подход для того же. Каждый раз, когда я бегу npm run electron
я вижу, что электронное окно открывается. Название, из которого он берет public/index.html
отображается нормально. Но ничего в главном окне не появляется. Это просто показывает мне белый экран на заднем плане. Там нет ошибок в openDevTools console
тоже. Когда я закрываю электронное приложение, оно закрывается BrowserWindow
, Можете ли вы помочь мне решить эту проблему. Пожалуйста, найдите ниже детали кода.
main.js
файл находится в electron/main.js
const electron = require("electron");
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const path = require("path");
const url = require("url");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({ width: 800, height: 600 });
const startUrl =
process.env.ELECTRON_START_URL ||
url.format({
pathname: path.join(__dirname, "../public/index.html"),
protocol: "file:",
slashes: true
});
mainWindow.loadURL(startUrl);
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on("closed", () => {
mainWindow = null;
});
}
app.on("ready", createWindow);
// Quit when all windows are closed.
app.on("window-all-closed", function() {
// 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", function() {
// 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.
index.html
файл находится в public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://apis.google.com/js/platform.js"></script>
<script src="https://apis.google.com/js/api.js" async defer></script>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<script src="https://apis.google.com/js/api:client.js" async defer></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!-- <meta name="google-signin-client_id" content="223952078588-2k28dh7rc6oom6pdnicbhcjlkoh207nb.apps.googleusercontent.com"> -->
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico " or "favicon.ico ", "%PUBLIC_URL%/favicon.ico " will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet">
<title>My Burger</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
electron-wait-react.js
находится в проекте root
каталог. Файл в основном отвечает за то, чтобы позволить сначала реагировать нагрузке, а затем электрону.
const net = require("net");
const port = process.env.PORT ? process.env.PORT - 100 : 5000;
// import * as from "./electron/main"
process.env.ELECTRON_START_URL = `http://localhost:${port}`;
const client = new net.Socket();
let startedElectron = false;
const tryConnection = () =>
client.connect({ port: port }, () => {
client.end();
if (!startedElectron) {
console.log("starting electron");
startedElectron = true;
const exec = require("child_process").exec;
exec("npm run electron");
}
});
tryConnection();
client.on("error", error => {
setTimeout(tryConnection, 1000);
});
package.json
файл находится в проекте root
каталог.
{
"name": "burger-builder-app",
"version": "0.1.0",
"private": true,
"main": "electron/main",
"dependencies": {
"autoprefixer": "7.1.6",
"axios": "^0.18.0",
"babel-core": "6.26.0",
"babel-eslint": "7.2.3",
"babel-jest": "20.0.3",
"babel-loader": "7.1.2",
"babel-preset-react-app": "^3.1.1",
"babel-runtime": "6.26.0",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
"css-loader": "0.28.7",
"dotenv": "4.0.0",
"dotenv-expand": "4.2.0",
"electron": "^2.0.2",
"electron-builder": "^20.14.7",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "4.10.0",
"eslint-config-react-app": "^2.1.0",
"eslint-loader": "1.9.0",
"eslint-plugin-flowtype": "2.39.1",
"eslint-plugin-import": "2.8.0",
"eslint-plugin-jsx-a11y": "5.1.1",
"eslint-plugin-react": "7.4.0",
"extract-text-webpack-plugin": "3.0.2",
"file-loader": "1.1.5",
"firebase": "^4.13.1",
"foreman": "^3.0.0",
"fs-extra": "3.0.1",
"html-webpack-plugin": "2.29.0",
"jest": "20.0.4",
"object-assign": "4.1.1",
"postcss-flexbugs-fixes": "3.2.0",
"postcss-loader": "2.0.8",
"promise": "8.0.1",
"prop-types": "^15.6.1",
"raf": "3.4.0",
"react": "^16.2.0",
"react-dev-utils": "^5.0.0",
"react-dom": "^16.2.0",
"react-redux": "^5.0.7",
"react-router-dom": "^4.2.2",
"react-test-renderer": "^16.3.2",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0",
"style-loader": "0.19.0",
"sw-precache-webpack-plugin": "0.11.4",
"url-loader": "0.6.2",
"webpack": "3.8.1",
"webpack-dev-server": "2.9.4",
"webpack-manifest-plugin": "1.3.2",
"whatwg-fetch": "2.0.3"
},
"scripts": {
"dev": "nf start",
"start": "node scripts/start.js",
"build": "rm -rf build && node scripts/build.js",
"test": "node scripts/test.js --env=jsdom",
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"electron": "electron .",
"ebuild": "npm build && node_modules/.bin/build"
},
"description": "Burger Builder App",
"build": {
"electronVersion": "2.0.2",
"files": ["build/**/*", "electron/*"]
},
"jest": {
"collectCoverageFrom": ["src/**/*.{js,jsx,mjs}"],
"setupFiles": ["<rootDir>/config/polyfills.js"],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)":
"<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"mjs",
"js",
"json",
"web.jsx",
"jsx",
"node"
]
},
"babel": {
"presets": ["react-app"]
},
"eslintConfig": {
"extends": "react-app"
},
"devDependencies": {
"gh-pages": "^1.1.0"
}
}
Procfile
в root
каталог.
react: npm ./scripts/start.js
electron: node electron-wait-react.js