Skip to content

Commit 54e3409

Browse files
committed
修改配置
1 parent 7fb7e54 commit 54e3409

File tree

11 files changed

+309
-295
lines changed

11 files changed

+309
-295
lines changed

.env.development

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#环境变量
2-
NODE_ENV="development"
2+
NODE_ENV=development
33
VITE_APP_BASEAPI="https://www.dev.com"
4-
VITE_PROJECT_TITLE="标题"
5-
NODE_ENV='development'
4+
VITE_PROJECT_TITLE="标题"

bin/cmd.js

+110-100
Original file line numberDiff line numberDiff line change
@@ -6,126 +6,136 @@
66
* @FilePath: /react-loading-ssr/bin/cmd.js
77
* @Description:
88
*/
9-
import os from 'os'
10-
import { spawn, SpawnOptions, exec, execSync } from 'child_process'
11-
import moment from 'moment'
12-
9+
import os from 'os';
10+
import { spawn, SpawnOptions, exec, execSync } from 'child_process';
11+
import moment from 'moment';
1312

1413
export default class Cmd {
15-
text = ''
16-
17-
runNodeModule(moduleName, params, options) {
18-
if (os.type() == 'Windows_NT' && !moduleName.match(/\.cmd$/)) {
19-
moduleName += '.cmd'
20-
}
21-
return this.run(moduleName, params, options)
22-
}
23-
24-
run(command, params, options) {
25-
this.text = ''
26-
// options = Object.assign(options || {}, { cwd: this.cfg.cwd });
27-
return new Promise((resolve, reject) => {
28-
console.log(`run command: ${command}, params:`, params, options)
29-
30-
if (!options) {
31-
options = {
32-
stdio: 'inherit',
33-
}
34-
}
35-
if (!params) params = []
36-
options.stdio = 'pipe'
37-
38-
let proc = spawn(command, params, options)
39-
// console.log('proc===', proc)
14+
text = '';
4015

41-
proc.stdout.on('data', (data) => {
42-
let dataStr = String(data)
43-
if (options.logPrefix) {
44-
dataStr = options.logPrefix + dataStr
16+
runNodeModule(moduleName, params, options) {
17+
if (os.type() == 'Windows_NT' && !moduleName.match(/\.cmd$/)) {
18+
moduleName += '.cmd';
4519
}
46-
this.text += dataStr
47-
if (!options?.silent)
48-
process.stdout.write(moment().format('HH:mm:ss:SSS ') + dataStr)
49-
})
50-
51-
proc.stderr.on('data', (data) => {
52-
// 不一定代表进程exitcode != 0,可能只是进程调用了console.error
53-
let dataStr = String(data)
54-
if (options?.logPrefix) {
55-
dataStr = options.logPrefix + dataStr
56-
}
57-
if (!options?.silent)
58-
process.stderr.write(moment().format('HH:mm:ss:SSS ') + dataStr)
59-
})
60-
61-
// 进程错误
62-
proc.on('error', (error) => {
63-
if (!options?.silent) console.error(error)
64-
reject(error)
65-
})
66-
67-
// 进程关闭
68-
proc.on('close', (code) => {
69-
console.log(`process closed with exit code: ${code}`)
70-
if (code == 0) {
71-
resolve(this.text || '')
72-
} else {
73-
let errMsg = `process closed with exit code: ${code}`
74-
if (options?.logPrefix) {
75-
errMsg = options.logPrefix + errMsg
76-
}
77-
reject(new Error(errMsg))
78-
}
79-
})
20+
return this.run(moduleName, params, options);
21+
}
8022

81-
proc.on('exit', (code, signal) => {
82-
console.log(`process exits`)
83-
})
84-
})
85-
}
23+
run(command, params, options) {
24+
this.text = '';
25+
// options = Object.assign(options || {}, { cwd: this.cfg.cwd });
26+
return new Promise((resolve, reject) => {
27+
console.log(`run command: ${command}, params:`, params, options);
28+
29+
if (!options) {
30+
options = {
31+
stdio: 'inherit',
32+
};
33+
}
34+
if (!params) params = [];
35+
options.stdio = 'pipe';
36+
37+
let proc = spawn(command, params, options);
38+
// console.log('proc===', proc)
39+
40+
proc.stdout.on('data', (data) => {
41+
let dataStr = String(data);
42+
if (options.logPrefix) {
43+
dataStr = options.logPrefix + dataStr;
44+
}
45+
this.text += dataStr;
46+
if (!options?.silent)
47+
process.stdout.write(
48+
moment().format('HH:mm:ss:SSS ') + dataStr
49+
);
50+
});
51+
52+
proc.stderr.on('data', (data) => {
53+
// 不一定代表进程exitcode != 0,可能只是进程调用了console.error
54+
let dataStr = String(data);
55+
if (options?.logPrefix) {
56+
dataStr = options.logPrefix + dataStr;
57+
}
58+
if (!options?.silent)
59+
process.stderr.write(
60+
moment().format('HH:mm:ss:SSS ') + dataStr
61+
);
62+
});
63+
64+
// 进程错误
65+
proc.on('error', (error) => {
66+
if (!options?.silent) console.error(error);
67+
reject(error);
68+
});
69+
70+
// 进程关闭
71+
proc.on('close', (code) => {
72+
console.log(`process closed with exit code: ${code}`);
73+
if (code == 0) {
74+
resolve(this.text || '');
75+
} else {
76+
let errMsg = `process closed with exit code: ${code}`;
77+
if (options?.logPrefix) {
78+
errMsg = options.logPrefix + errMsg;
79+
}
80+
reject(new Error(errMsg));
81+
}
82+
});
83+
84+
proc.on('exit', (code, signal) => {
85+
console.log(`process exits`);
86+
});
87+
});
88+
}
8689
}
8790

8891
// let cmd = new Cmd().runNodeModule(
8992
// process.platform === 'win32' ? 'npm.cmd' : 'npm',
9093
// ['run', 'ssr:dev', '--progress', 'bar:force'],
9194
// )
9295

93-
export const execute = (command, args = [], options = { stdio: 'inherit' }) => {
94-
const proc = spawn(command, args, options)
96+
export const execute = (command, options = { stdio: 'inherit' }) => {
97+
command = command.split(' ').filter((item) => item);
9598

96-
// 进程错误
97-
proc.on('error', (error) => {
98-
if (error) console.error(error)
99-
})
99+
if (os.type() === 'Windows_NT' && !command[0].match(/\.cmd$/)) {
100+
command[0] += '.cmd';
101+
}
100102

101-
// 进程关闭
102-
proc.on('close', (code) => {
103-
console.log(`process closed with exit code: ${code}`)
104-
})
103+
const proc = spawn(command[0], command.slice(1), options);
105104

106-
// 退出
107-
proc.on('exit', (code, signal) => {
108-
console.log(`process exits`)
109-
})
105+
// 进程错误
106+
proc.on('error', (error) => {
107+
if (error) console.error(error);
108+
});
110109

111-
return proc
112-
}
110+
// 进程关闭
111+
proc.on('close', (code) => {
112+
console.log(`process closed with exit code: ${code}`);
113+
});
114+
115+
// 退出
116+
proc.on('exit', (code, signal) => {
117+
console.log(`process exits`);
118+
});
119+
120+
return proc;
121+
};
113122

114123
/**
115124
* 判断端口是否被占用
116125
* @param port 端口号
117126
* @returns 该端口是否被占用
118127
*/
119128
export const iSportTake = (port) => {
120-
const cmd = process.platform === 'win32' ? 'netstat -aon|findstr' : 'lsof -i:'
121-
122-
let order = `${cmd}${port}`
123-
124-
try {
125-
const res = execSync(order)
126-
return true
127-
} catch (error) {
128-
console.log('error:', error)
129-
}
130-
return false
131-
}
129+
const cmd =
130+
process.platform === 'win32'
131+
? `netstat -aon|findstr ${port}`
132+
: `lsof -i:${port}`;
133+
try {
134+
const res = execSync(cmd);
135+
return true;
136+
} catch (error) {
137+
// console.log('error:', error);
138+
return false;
139+
}
140+
141+
};

bin/index.js

+77-55
Original file line numberDiff line numberDiff line change
@@ -6,64 +6,86 @@
66
* @FilePath: /react-loading-ssr/bin/index.js
77
* @Description:
88
*/
9-
import cluster from 'cluster'
10-
import path from 'path'
11-
import os from 'os'
12-
import * as dotenv from 'dotenv'
13-
import { Worker } from 'worker_threads'
14-
import { copyFile, watchFile, readWriteFiles } from '../webpack/utils'
15-
import { spawn, SpawnOptions } from 'child_process'
16-
import kill from 'kill-port' // 杀死端口包
17-
import { execute, iSportTake } from './cmd' // 杀死端口包
18-
import { stabilization } from '../client/utils'
19-
// 注入环境变量
20-
dotenv.config({ path: '.env' })
9+
import cluster from 'cluster';
10+
import path from 'path';
11+
import os from 'os';
12+
import { Worker } from 'worker_threads';
13+
import { copyFile, watchFile, readWriteFiles } from '../webpack/utils';
14+
import { spawn, SpawnOptions } from 'child_process';
15+
import kill from 'kill-port'; // 杀死端口包
16+
import { execute, iSportTake } from './cmd'; // 杀死端口包
17+
import { stabilization } from '../client/utils';
18+
import ResolveAlias from '../webpack/definePlugin/webpack-plugin-resolve-alias';
19+
20+
import * as dotenv from 'dotenv';
21+
dotenv.config({ path: '.env' });
22+
2123
// 如果是开发环境 先拷贝 服务器文件到 dist
2224
let {
23-
NODE_ENV, // 环境参数
24-
WEB_ENV, // 环境参数
25-
target, // 环境参数
26-
htmlWebpackPluginOptions = '',
27-
port,
28-
} = process.env // 环境参数
29-
console.log('target=======', target)
30-
const isSsr = target === 'ssr'
25+
NODE_ENV, // 环境参数
26+
WEB_ENV, // 环境参数
27+
target, // 环境参数
28+
htmlWebpackPluginOptions = '',
29+
port,
30+
} = process.env; // 环境参数
31+
32+
const isSsr = target === 'ssr';
3133
// 是否是生产环境
32-
const isEnvProduction = NODE_ENV === 'production'
34+
const isEnvProduction = NODE_ENV === 'production';
3335
// 是否是测试开发环境
34-
const isEnvDevelopment = NODE_ENV === 'development'
35-
let counter = 0
36-
let child = null
36+
const isEnvDevelopment = NODE_ENV === 'development';
37+
38+
console.log('NODE_ENV======', NODE_ENV);
39+
40+
let counter = 0;
41+
let child = null;
3742
if (isEnvDevelopment && isSsr) {
38-
readWriteFiles({
39-
from: path.join(process.cwd(), '/server/**/*').replace(/\\/gi, '/'),
40-
to: path.join(process.cwd(), '/dist/server').replace(/\\/gi, '/'),
41-
transform(content, absoluteFrom) {
42-
// let reg = /.jsx|.js$/g;
43-
// if (reg.test(absoluteFrom)) {
44-
// return $ResolveAlias.alias(content.toString(), '');
45-
// }
46-
return content
47-
},
48-
callback() {
49-
counter += 1
50-
if (child) {
51-
// spawn 杀死正在执行的子进程
52-
var kill = spawn('kill', [child.pid])
53-
}
54-
stabilization(300, () => {
55-
if (counter === 1) {
56-
child = execute(process.platform === 'win32' ? 'npm.cmd' : 'npm', [
57-
'run',
58-
'ssr:dev',
59-
])
60-
} else {
61-
child = execute(process.platform === 'win32' ? 'npm.cmd' : 'npm', [
62-
'run',
63-
'bin',
64-
])
65-
}
66-
})
67-
},
68-
})
43+
let $ResolveAlias = new ResolveAlias({
44+
resolve: {
45+
// 路径配置
46+
alias: {
47+
'@/': path.join(process.cwd(), '/client'),
48+
},
49+
},
50+
});
51+
52+
readWriteFiles({
53+
from: path.join(process.cwd(), '/server/**/*').replace(/\\/gi, '/'),
54+
to: path.join(process.cwd(), '/dist/server').replace(/\\/gi, '/'),
55+
transform(content, absoluteFrom) {
56+
let reg = /.jsx|.js$/g;
57+
if (reg.test(absoluteFrom)) {
58+
return $ResolveAlias.alias(content.toString(), '');
59+
}
60+
return content;
61+
},
62+
async callback() {
63+
if (child) {
64+
// spawn 杀死正在执行的子进程
65+
spawn('kill', [child.pid]);
66+
}
67+
68+
if (iSportTake(port)) {
69+
await kill(port, 'tcp');
70+
}
71+
stabilization(500, async () => {
72+
counter += 1;
73+
if (counter === 1) {
74+
child = execute(
75+
"cross-env target='ssr' npx babel-node -r @babel/register ./server/index.js -r dotenv/config dotenv_config_path=.env.development"
76+
);
77+
} else {
78+
child = execute('npm run bin');
79+
counter = 0;
80+
}
81+
});
82+
},
83+
});
6984
}
85+
86+
// if (isEnvDevelopment && !isSsr) {
87+
// execute(process.platform === 'win32' ? 'npm.cmd' : 'npm', [
88+
// 'run',
89+
// 'ssr:dev',
90+
// ]);
91+
// }

0 commit comments

Comments
 (0)