Skip to content

Commit

Permalink
support preload.ts (#3155)
Browse files Browse the repository at this point in the history
  • Loading branch information
sminf authored Mar 22, 2022
1 parent 8aa6ff5 commit 5b4fa97
Show file tree
Hide file tree
Showing 10 changed files with 159 additions and 21 deletions.
2 changes: 1 addition & 1 deletion .erb/configs/webpack.config.main.prod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const configuration: webpack.Configuration = {

entry: {
main: path.join(webpackPaths.srcMainPath, 'main.ts'),
preload: path.join(webpackPaths.srcMainPath, 'preload.js'),
preload: path.join(webpackPaths.srcMainPath, 'preload.ts'),
},

output: {
Expand Down
68 changes: 68 additions & 0 deletions .erb/configs/webpack.config.preload.dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import path from 'path';
import webpack from 'webpack';
import { merge } from 'webpack-merge';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
import checkNodeEnv from '../scripts/check-node-env';

// When an ESLint server is running, we can't set the NODE_ENV so we'll check if it's
// at the dev webpack config is not accidentally run in a production environment
if (process.env.NODE_ENV === 'production') {
checkNodeEnv('development');
}

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

mode: 'development',

target: 'electron-preload',

entry: path.join(webpackPaths.srcMainPath, 'preload.ts'),

output: {
path: webpackPaths.dllPath,
filename: 'preload.js',
},

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

/**
* 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
*
* By default, use 'development' as NODE_ENV. This can be overriden with
* 'staging', for example, by changing the ENV variables in the npm scripts
*/
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
}),

new webpack.LoaderOptionsPlugin({
debug: true,
}),
],

/**
* Disables webpack processing of __dirname and __filename.
* If you run the bundle in node.js it falls back to these values of node.js.
* https://github.com/webpack/webpack/issues/2010
*/
node: {
__dirname: false,
__filename: false,
},

watch: true,
};

export default merge(baseConfig, configuration);
23 changes: 16 additions & 7 deletions .erb/configs/webpack.config.renderer.dev.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import 'webpack-dev-server';
import path from 'path';
import fs from 'fs';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import chalk from 'chalk';
import { merge } from 'webpack-merge';
import { spawn, execSync } from 'child_process';
import { execSync, spawn } from 'child_process';
import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
Expand Down Expand Up @@ -150,8 +151,6 @@ const configuration: webpack.Configuration = {
__filename: false,
},

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
devServer: {
port,
compress: true,
Expand All @@ -163,16 +162,26 @@ const configuration: webpack.Configuration = {
historyApiFallback: {
verbose: true,
},
onBeforeSetupMiddleware() {
setupMiddlewares(middlewares) {
console.log('Starting preload.js builder...');
const preloadProcess = spawn('npm', ['run', 'start:preload'], {
shell: true,
stdio: 'inherit',
})
.on('close', (code: number) => process.exit(code!))
.on('error', (spawnError) => console.error(spawnError));

console.log('Starting Main Process...');
spawn('npm', ['run', 'start:main'], {
shell: true,
env: process.env,
stdio: 'inherit',
})
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
.on('close', (code: number) => process.exit(code!))
.on('close', (code: number) => {
preloadProcess.kill();
process.exit(code!);
})
.on('error', (spawnError) => console.error(spawnError));
return middlewares;
},
},
};
Expand Down
40 changes: 40 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"postinstall": "ts-node .erb/scripts/check-native-dep.js && electron-builder install-app-deps && cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.renderer.dev.dll.ts && opencollective-postinstall",
"start": "ts-node ./.erb/scripts/check-port-in-use.js && npm run start:renderer",
"start:main": "cross-env NODE_ENV=development electron -r ts-node/register/transpile-only ./src/main/main.ts",
"start:preload": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.preload.dev.ts",
"start:renderer": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack serve --config ./.erb/configs/webpack.config.renderer.dev.ts",
"test": "jest",
"prepare": "husky install"
Expand Down Expand Up @@ -169,6 +170,7 @@
"@types/react-dom": "^17.0.11",
"@types/react-test-renderer": "^17.0.1",
"@types/terser-webpack-plugin": "^5.0.4",
"@types/webpack-bundle-analyzer": "^4.4.1",
"@types/webpack-env": "^1.16.3",
"@typescript-eslint/eslint-plugin": "^5.8.1",
"@typescript-eslint/parser": "^5.8.1",
Expand Down
4 changes: 3 additions & 1 deletion src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ const createWindow = async () => {
height: 728,
icon: getAssetPath('icon.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
preload: app.isPackaged
? path.join(__dirname, 'preload.js')
: path.join(__dirname, '../../.erb/dll/preload.js'),
},
});

Expand Down
12 changes: 7 additions & 5 deletions src/main/preload.js → src/main/preload.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
const { contextBridge, ipcRenderer } = require('electron');
import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('electron', {
ipcRenderer: {
myPing() {
ipcRenderer.send('ipc-example', 'ping');
},
on(channel, func) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
on(channel: string, func: (...args: any[]) => void) {
const validChannels = ['ipc-example'];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => func(...args));
ipcRenderer.on(channel, (_event, ...args) => func(...args));
}
},
once(channel, func) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
once(channel: string, func: (...args: any[]) => void) {
const validChannels = ['ipc-example'];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.once(channel, (event, ...args) => func(...args));
ipcRenderer.once(channel, (_event, ...args) => func(...args));
}
},
},
Expand Down
7 changes: 0 additions & 7 deletions src/renderer/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,4 @@
<body>
<div id="root"></div>
</body>
<script>
window.electron.ipcRenderer.once('ipc-example', (arg) => {
console.log(arg);
});
window.electron.ipcRenderer.myPing();
</script>
</html>
7 changes: 7 additions & 0 deletions src/renderer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,10 @@ import { render } from 'react-dom';
import App from './App';

render(<App />, document.getElementById('root'));

// calling IPC exposed from preload script
window.electron.ipcRenderer.once('ipc-example', (arg) => {
// eslint-disable-next-line no-console
console.log(arg);
});
window.electron.ipcRenderer.myPing();
15 changes: 15 additions & 0 deletions src/renderer/preload.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
declare global {
interface Window {
electron: {
ipcRenderer: {
myPing(): void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
on(channel: string, func: (...args: any[]) => void): void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
once(channel: string, func: (...args: any[]) => void): void;
};
};
}
}

export {};

0 comments on commit 5b4fa97

Please sign in to comment.