Skip to content

Commit 5436d41

Browse files
committed
node electron分支
1 parent f893d2b commit 5436d41

19 files changed

+199
-28
lines changed

index.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ function create(project) {
2222
function init(project) {
2323
console.info(`Init project ${project}`);
2424
const DIR_APP = path.resolve(project, '.');
25-
const DIR_APP_TEMPLATE = path.resolve(__dirname, './public/app'); // 项目模板
25+
const DIR_APP_TEMPLATE = path.resolve(__dirname, `./public/${globalThis.kind === 'electron' ? 'electron-app' : 'node-app'}`); // 项目模板
2626
fs.copySync(DIR_APP_TEMPLATE, DIR_APP);
2727
eject(project);
2828
console.log(`A electron-main project init succeed! To continue, please:\n\ncd ${project}\nyarn setup`);
@@ -37,6 +37,9 @@ function main() {
3737
init(path.resolve(process.cwd(), process.argv[3] || '.'));
3838
break;
3939
}
40+
case '-ce': {
41+
globalThis.kind = 'electron';
42+
}
4043
case '-c':
4144
case 'create':
4245
case '--create': { // Create a project directory and init

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@develon/node-dev-server",
3-
"version": "1.6.0",
3+
"version": "1.7.0",
44
"description": "Serves a Node.js app. Restart the app on changes.",
55
"bin": {
66
"nds": "./bin/main.js",

public/app/src/index.ts

-24
This file was deleted.
File renamed without changes.

public/electron-app/package.json

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"name": "app",
3+
"version": "1.0.0",
4+
"main": "dist/main.js",
5+
"scripts": {
6+
"setup": "nds --eject && yarn add -D @types/node file-loader",
7+
"start:dev": "nds",
8+
"build": "webpack --env production",
9+
"rebuild": "webpack --env rebuild"
10+
},
11+
"license": "MIT"
12+
}

public/app/src/index.html renamed to public/electron-app/src/index.html

+6-1
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,15 @@
99

1010
<body>
1111
<div id="app">
12-
<h1>
12+
<h1 id="info">
1313
Hello, Electron with TypeScirpt!
1414
</h1>
15+
<p id="output">Click it to see the effect in this interface.</p>
16+
<button onclick="notify()">Test</button>
17+
<button onclick="exit()">Exit</button>
1518
</div>
19+
20+
<script src="renderer.js"></script>
1621
</body>
1722

1823
</html>

public/electron-app/src/index.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import electron from 'electron';
2+
import path from 'path';
3+
// @ts-ignore
4+
import html from '!file-loader?name=[name].[ext]!./index.html';
5+
// @ts-ignore
6+
import renderer from '!file-loader?name=[name].js!./renderer';
7+
8+
var app = electron.app;
9+
var win: electron.BrowserWindow;
10+
11+
async function main() {
12+
await app.whenReady();
13+
win = new electron.BrowserWindow({
14+
width: 1680,
15+
height: 800,
16+
webPreferences: {
17+
nodeIntegration: false, // 集成Node.js
18+
nodeIntegrationInWorker: false, // WebWorker中集成Node.js
19+
// 即使使用了nodeIntegration: false,为了真正执行强隔离并防止使用Node基元,还必须使用contextIsolation。
20+
contextIsolation: true, // 上下文隔离
21+
enableRemoteModule: false, // 远程模块
22+
preload: path.resolve(__dirname, `preload.js`), // 预加载脚本
23+
},
24+
});
25+
console.log({ __dirname, html, renderer });
26+
win.loadFile(html);
27+
win.webContents.openDevTools();
28+
enableAPI();
29+
}
30+
31+
function enableAPI() {
32+
electron.ipcMain.on('bye', (_, millis) => {
33+
console.log(`System will exit after ${millis} ms.`);
34+
setTimeout(() => {
35+
process.exit(0);
36+
}, millis);
37+
});
38+
}
39+
40+
main();

public/electron-app/src/preload.ts

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { contextBridge, ipcRenderer } from "electron";
2+
import { userInfo } from "os";
3+
4+
// 暴露接口
5+
const myAPI = {
6+
getUserName() {
7+
// 即使开启上下文隔离,预加载脚本仍然可以通过contextBridge将Node.js功能暴露给渲染脚本
8+
return userInfo().username;
9+
},
10+
ipcRenderer,
11+
};
12+
contextBridge.exposeInMainWorld('myAPI', myAPI);
13+
14+
window.addEventListener('DOMContentLoaded', () => {
15+
// 预加载脚本可以访问document
16+
var h1: HTMLHeadElement = document.querySelector('h1#info');
17+
h1.innerText = `Hello, ${myAPI.getUserName()}`;
18+
});

public/electron-app/src/renderer.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const NOTIFICATION_TITLE = 'Title'
2+
const NOTIFICATION_BODY = 'Notification from the Renderer process. Click to log to console.'
3+
const CLICK_MESSAGE = 'Notification clicked!'
4+
5+
6+
function notify() {
7+
new Notification(NOTIFICATION_TITLE, { body: NOTIFICATION_BODY })
8+
.onclick = () => document.getElementById("output").innerText = CLICK_MESSAGE
9+
}
10+
11+
function exit() {
12+
myAPI.ipcRenderer.send('bye', 2000);
13+
}
14+
15+
console.log(myAPI.getUserName());

public/electron-app/tsconfig.json

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/*
2+
* Generated by node-dev-server, will not affect compilation of webpack, cause using babel-loader.
3+
*
4+
* @author Develon (https://github.com/develon2015)
5+
*/
6+
7+
{
8+
"compilerOptions": {
9+
"target": "ES6",
10+
"lib": ["ES6", "DOM"],
11+
"module": "CommonJS",
12+
"moduleResolution": "Node",
13+
"baseUrl": ".",
14+
"paths": {
15+
"@/*": ["src/*"],
16+
},
17+
"allowSyntheticDefaultImports": true,
18+
},
19+
"exclude": ["node_modules"],
20+
}

public/electron-app/webpack.config.js

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
* Generated by node-dev-server
3+
*
4+
* @author Develon (https://github.com/develon2015)
5+
*/
6+
const $babel_loader = require('./nds-babel.js'); // nds plugin
7+
8+
const path = require('path');
9+
10+
const DIR_PROJECT = path.resolve(__dirname, '.');
11+
const DIR_SRC = path.resolve(DIR_PROJECT, 'src');
12+
const DIR_DIST = path.resolve(DIR_PROJECT, 'dist');
13+
14+
/**
15+
* @type {import('webpack').Configuration}
16+
*/
17+
const CONFIG = {
18+
// target: 'node', // 请本地安装开发依赖: @types/node
19+
target: 'electron-main', // electron主进程支持. 可以全局安装electron, 然后link到本地, 以提供相应版本的electron类型支持.
20+
// target: 'electron-renderer', // electron渲染进程不需要使用nds, 请使用: webpack-dev-server + webpack serve
21+
mode: 'none', // 开发时不建议使用默认值"production"
22+
// mode: 'development', // 开发模式
23+
// devtool: 'source-map', // 生成main.js.map源码映射文件, 以支持.ts源码的断点调试。还可以使用inline-source-map
24+
entry: {
25+
main: path.resolve(DIR_SRC),
26+
preload: path.resolve(DIR_SRC, 'preload'),
27+
},
28+
output: {
29+
filename: '[name].js',
30+
path: DIR_DIST,
31+
libraryTarget: 'commonjs2',
32+
chunkFilename: 'async/[id]-module-[name].js', // 此选项确定非入口块文件的名称
33+
},
34+
module: {
35+
rules: [
36+
{ test: /\.tsx?$/, exclude: /node_modules/, use: $babel_loader }, // @BABEL_LOADER及其预设由nds提供
37+
],
38+
},
39+
resolve: {
40+
extensions: ['.ts', '.js', '.json', '.tsx'],
41+
alias: {
42+
'@': DIR_SRC,
43+
},
44+
},
45+
};
46+
47+
function config(env = {}, argv = {}) {
48+
if (env && (env.production || env.rebuild)) {
49+
console.log('Build production');
50+
CONFIG.mode = 'production';
51+
delete CONFIG.devtool;
52+
delete CONFIG.devServer;
53+
}
54+
if (env && env.rebuild) {
55+
console.log('Rebuild production');
56+
console.log('OS:', process.platform);
57+
try {
58+
const child_process = require('child_process');
59+
if (process.platform.match(/^win.*/)) { // Implement this on Windows OS
60+
child_process.execSync(`rmdir /S /Q "${DIR_DIST}"`);
61+
} else if (process.platform.match(/^linux.*/)) { // Implement this on Linux OS
62+
child_process.execSync(`rm -rf '${DIR_DIST}'`);
63+
}
64+
} catch (error) { }
65+
}
66+
return CONFIG;
67+
}
68+
69+
module.exports = config;

public/node-app/.gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
node_modules
2+
dist
3+
test
4+
5+
nds-babel.js
File renamed without changes.

public/node-app/src/index.ts

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import os from 'os';
2+
3+
function main() {
4+
console.log('Hello,', os.platform(), os.arch());
5+
}
6+
7+
main();

public/app/tsconfig.json renamed to public/node-app/tsconfig.json

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"paths": {
1515
"@/*": ["src/*"],
1616
},
17+
"allowSyntheticDefaultImports": true,
1718
},
1819
"exclude": ["node_modules"],
1920
}
File renamed without changes.

webpack-externals.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ function excludeNodeModules({ context, request }, callback) { // 官网和CLI提
4343
let instruction = `require('${request}')`;
4444
console.log('运行时模块:', `${request}由node_modules提供 => ${request} = ${instruction}`);
4545
if (_libraryTarget === 'umd' || _libraryTarget === 'commonjs' || _libraryTarget === 'commonjs2') {
46-
console.info('UMD 或 CommonJS 模式');
46+
// console.info('UMD 或 CommonJS 模式');
4747
return void callback(/*没有错误*/null, request); // 直接返回模块名, 而无需通过callback返回字符串`require(${request})`
4848
}
4949
return void callback(/*没有错误*/null, instruction);

0 commit comments

Comments
 (0)