fix: 修复一些bug

This commit is contained in:
wanchun 2022-05-06 13:10:09 +08:00
parent 5724cbd8f3
commit 443879bf4f
9 changed files with 74 additions and 71 deletions

View File

@ -4,7 +4,7 @@ import viteMiddlewarePlugin from './viteMiddlewarePlugin';
export default async (api, args) => { export default async (api, args) => {
const { deepmerge, getPort, changePort, getHostName } = api.utils; const { deepmerge, getPort, changePort, getHostName } = api.utils;
const port = await getPort(args.port || api.config.viteOption.server?.port); const port = await getPort(process.env.PORT || args.port || api.config.viteOption.server?.port);
changePort(port); changePort(port);
const hostname = getHostName(api.config.viteOption.server?.host); const hostname = getHostName(api.config.viteOption.server?.host);

View File

@ -34,7 +34,7 @@ export default (api) => {
type: api.ApplyPluginsType.event, type: api.ApplyPluginsType.event,
}); });
api.startWatch(); await api.startWatch();
server = await createServer(await getDevConfig(api, args)); server = await createServer(await getDevConfig(api, args));
await server.listen(); await server.listen();

View File

@ -4,13 +4,7 @@ import webpack from 'webpack';
export function startDevServer({ webpackConfig, host, port, proxy, https, beforeMiddlewares, afterMiddlewares, customerDevServerConfig }) { export function startDevServer({ webpackConfig, host, port, proxy, https, beforeMiddlewares, afterMiddlewares, customerDevServerConfig }) {
const options = { const options = {
hot: true, hot: true,
port,
host,
proxy,
allowedHosts: 'all', allowedHosts: 'all',
static: {
// contentBase: webpackConfig.output.path,
},
server: https ? 'https' : 'http', server: https ? 'https' : 'http',
client: { client: {
logging: 'error', logging: 'error',
@ -32,6 +26,9 @@ export function startDevServer({ webpackConfig, host, port, proxy, https, before
'access-control-allow-origin': '*', 'access-control-allow-origin': '*',
}, },
...(customerDevServerConfig || {}), ...(customerDevServerConfig || {}),
port,
host,
proxy,
}; };
const compiler = webpack(webpackConfig); const compiler = webpack(webpackConfig);
const server = new WebpackDevServer(options, compiler); const server = new WebpackDevServer(options, compiler);
@ -41,5 +38,6 @@ export function startDevServer({ webpackConfig, host, port, proxy, https, before
console.error(err); console.error(err);
} }
}); });
return server; return server;
} }

View File

@ -1,18 +1,18 @@
import { Logger } from '@fesjs/compiler';
const logger = new Logger('fes:build-webpack');
export default (api) => { export default (api) => {
const { const {
paths, paths,
utils: { chalk, getPort, getHostName, changePort }, utils: { chalk, getPort, getHostName, changePort },
} = api; } = api;
const unwatchs = [];
let port; let port;
let hostname; let hostname;
let server; let server;
async function destroy() { async function destroy() {
for (const unwatch of unwatchs) {
unwatch();
}
await server?.stop(); await server?.stop();
} }
@ -33,7 +33,8 @@ export default (api) => {
const { cleanTmpPathExceptCache, getBundleAndConfigs } = require('../buildDevUtils'); const { cleanTmpPathExceptCache, getBundleAndConfigs } = require('../buildDevUtils');
const connectHistoryMiddleware = require('./connectHistoryMiddleware').default; const connectHistoryMiddleware = require('./connectHistoryMiddleware').default;
port = await getPort(args.port || api.config.devServer?.port); port = await getPort(process.env.PORT || args.port || api.config.devServer?.port);
changePort(port); changePort(port);
hostname = getHostName(api.config.devServer?.host); hostname = getHostName(api.config.devServer?.host);
@ -50,7 +51,7 @@ export default (api) => {
type: api.ApplyPluginsType.event, type: api.ApplyPluginsType.event,
}); });
api.startWatch(); await api.startWatch();
// dev // dev
const { bundleConfig } = await getBundleAndConfigs({ api }); const { bundleConfig } = await getBundleAndConfigs({ api });
@ -67,6 +68,7 @@ export default (api) => {
initialValue: [], initialValue: [],
args: {}, args: {},
}); });
const { startDevServer } = require('./devServer'); const { startDevServer } = require('./devServer');
server = startDevServer({ server = startDevServer({
webpackConfig: bundleConfig, webpackConfig: bundleConfig,
@ -78,6 +80,7 @@ export default (api) => {
afterMiddlewares: [...middlewares], afterMiddlewares: [...middlewares],
customerDevServerConfig: api.config.devServer, customerDevServerConfig: api.config.devServer,
}); });
return { return {
destroy, destroy,
}; };
@ -87,7 +90,7 @@ export default (api) => {
api.registerMethod({ api.registerMethod({
name: 'restartServer', name: 'restartServer',
fn() { fn() {
console.log(chalk.gray('Try to restart dev server...')); logger.info(chalk.gray('Try to restart dev server...'));
destroy(); destroy();
process.send({ process.send({
type: 'RESTART', type: 'RESTART',

View File

@ -3,10 +3,7 @@
* https://github.com/umijs/umi/tree/master/packages/core * https://github.com/umijs/umi/tree/master/packages/core
*/ */
import { import { createDebug, chalk } from '@fesjs/utils';
createDebug,
chalk
} from '@fesjs/utils';
import readline from 'readline'; import readline from 'readline';
export default class Logger { export default class Logger {
@ -52,9 +49,7 @@ export default class Logger {
} }
formatTiming(timing) { formatTiming(timing) {
return timing < 60 * 1000 return timing < 60 * 1000 ? `${Math.round(timing / 10) / 100}s` : `${Math.round(timing / 600) / 100}m`;
? `${Math.round(timing / 10) / 100}s`
: `${Math.round(timing / 600) / 100}m`;
} }
profile(id, message) { profile(id, message) {
@ -66,9 +61,7 @@ export default class Logger {
const timeEnd = this.profilers[id]; const timeEnd = this.profilers[id];
delete this.profilers[id]; delete this.profilers[id];
process.stderr.write(`${this.PROFILE} `); process.stderr.write(`${this.PROFILE} `);
msg = `${this.PROFILE} ${chalk.cyan( msg = `${this.PROFILE} ${chalk.cyan(`${namespace}`)} Completed in ${this.formatTiming(time - timeEnd)}`;
`${namespace}`
)} Completed in ${this.formatTiming(time - timeEnd)}`;
console.log(msg); console.log(msg);
} else { } else {
msg = `${this.PROFILE} ${chalk.cyan(`${namespace}`)} ${message || ''}`; msg = `${this.PROFILE} ${chalk.cyan(`${namespace}`)} ${message || ''}`;

View File

@ -16,11 +16,8 @@ export default function (api) {
'addEntryCodeAhead', 'addEntryCodeAhead',
'addEntryCode', 'addEntryCode',
'modifyRoutes', 'modifyRoutes',
'addConfigType', 'addConfigType',
'addTmpGenerateWatcherPaths', 'addTmpGenerateWatcherPaths',
'addBeforeMiddlewares', 'addBeforeMiddlewares',
'addMiddlewares', 'addMiddlewares',
].forEach((name) => { ].forEach((name) => {

View File

@ -47,7 +47,7 @@ export async function startWatch(api) {
if (process.env.WATCH === 'none') return; if (process.env.WATCH === 'none') return;
let unwatchs = []; let unwatchs = [];
const destroy = () => { const restartServer = () => {
for (const unwatch of unwatchs) { for (const unwatch of unwatchs) {
unwatch(); unwatch();
} }
@ -65,7 +65,7 @@ export async function startWatch(api) {
onChange() { onChange() {
console.log(); console.log();
api.logger.info('Plugins in package.json changed.'); api.logger.info('Plugins in package.json changed.');
destroy(); restartServer();
}, },
}); });
unwatchs.push(unwatchPkg); unwatchs.push(unwatchPkg);
@ -77,7 +77,7 @@ export async function startWatch(api) {
if (pluginChanged.length) { if (pluginChanged.length) {
console.log(); console.log();
api.logger.info(`Plugins of ${pluginChanged.map((p) => p.key).join(', ')} changed.`); api.logger.info(`Plugins of ${pluginChanged.map((p) => p.key).join(', ')} changed.`);
destroy(); restartServer();
} }
if (valueChanged.length) { if (valueChanged.length) {
let reload = false; let reload = false;
@ -101,7 +101,7 @@ export async function startWatch(api) {
if (reload) { if (reload) {
console.log(); console.log();
api.logger.info(`Config ${reloadConfigs.join(', ')} changed.`); api.logger.info(`Config ${reloadConfigs.join(', ')} changed.`);
destroy(); restartServer();
} else { } else {
api.service.userConfig = api.service.configInstance.getUserConfig(); api.service.userConfig = api.service.configInstance.getUserConfig();

View File

@ -3,33 +3,39 @@ export default function ({ cgiMock, mockjs, utils }) {
// 测试 proxy 与 mock 用例集合 // 测试 proxy 与 mock 用例集合
cgiMock('/movie/in_theaters_mock', (req, res) => { cgiMock('/movie/in_theaters_mock', (req, res) => {
res.send(JSON.stringify({ res.send(
code: '0', JSON.stringify({
msg: '', code: '0',
result: { msg: '',
text: 'movie: movie/in_theaters_mock ~~~~~' result: {
} text: 'movie: movie/in_theaters_mock ~~~~~',
})); },
}),
);
}); });
cgiMock('/movie/test_mock', (req, res) => { cgiMock('/movie/test_mock', (req, res) => {
res.send(JSON.stringify({ res.send(
code: '0', JSON.stringify({
msg: '', code: '0',
result: { msg: '',
text: 'mock: movie/test_mock' result: {
} text: 'mock: movie/test_mock',
})); },
}),
);
}); });
// 测试用例: mock.js change重现请求需要能拉最新的数据 // 测试用例: mock.js change重现请求需要能拉最新的数据
cgiMock('/watchtest', (req, res) => { cgiMock('/watchtest', (req, res) => {
res.send(JSON.stringify({ res.send(
code: '0', JSON.stringify({
msg: '', code: '0',
result: { msg: '',
text: '通过 register 测试 mock watch: 初始状态' result: {
} text: '通过 register 测试 mock watch: 初始状态',
})); },
}),
);
}); });
// 返回一个数字 // 返回一个数字
@ -40,17 +46,23 @@ export default function ({ cgiMock, mockjs, utils }) {
cgiMock({ cgiMock({
url: '/json', url: '/json',
result: { result: {
code: '400101', msg: "不合法的请求:Missing cookie 'wb_app_id' for method parameter of type String", transactionTime: '20170309171146', success: false code: '400101',
} msg: "不合法的请求:Missing cookie 'wb_app_id' for method parameter of type String",
transactionTime: '20170309171146',
success: false,
},
}); });
// 利用 mock.js 产生随机文本 // 利用 mock.js 产生随机文本
cgiMock('/text', Random.cparagraph()); cgiMock('/text', Random.cparagraph());
// 返回一个字符串 利用 mock.js 产生随机字符 // 返回一个字符串 利用 mock.js 产生随机字符
cgiMock('/random', mockjs.mock({ cgiMock(
'string|1-10': '★' '/random',
})); mockjs.mock({
'string|1-10': '★',
}),
);
// 正则匹配url, 返回一个字符串 // 正则匹配url, 返回一个字符串
cgiMock(/\/abc|\/xyz/, 'regexp test!'); cgiMock(/\/abc|\/xyz/, 'regexp test!');
@ -77,20 +89,21 @@ export default function ({ cgiMock, mockjs, utils }) {
headers: { headers: {
'Content-Type': 'text/plain', 'Content-Type': 'text/plain',
'Content-Length': '123', 'Content-Length': '123',
ETag: '12345' ETag: '12345',
}, },
cookies: [ cookies: [
{ {
name: 'myname', value: 'kwan', maxAge: 900000, httpOnly: true name: 'myname',
} value: 'kwan',
] maxAge: 900000,
httpOnly: true,
},
],
}); });
// 携带参数的请求 // 携带参数的请求
cgiMock('/v2/audit/list', (req, res) => { cgiMock('/v2/audit/list', (req, res) => {
const { const { currentPage, pageSize, isAudited } = req.body;
currentPage, pageSize, isAudited
} = req.body;
res.send({ res.send({
code: '0', code: '0',
msg: '', msg: '',
@ -114,9 +127,9 @@ export default function ({ cgiMock, mockjs, utils }) {
handleTag: '已采纳', handleTag: '已采纳',
postType: 'voice', postType: 'voice',
postStatus: isAudited ? 'pass' : 'auditing', postStatus: isAudited ? 'pass' : 'auditing',
auditStatus: 'audit1' auditStatus: 'audit1',
})) })),
} },
}); });
}); });
@ -124,7 +137,7 @@ export default function ({ cgiMock, mockjs, utils }) {
cgiMock('/v2/upload', (req, res) => { cgiMock('/v2/upload', (req, res) => {
res.send({ res.send({
code: '0', code: '0',
msg: '文件上传成功' msg: '文件上传成功',
}); });
}); });
} }

View File

@ -1,7 +1,6 @@
import portfinder from 'portfinder'; import portfinder from 'portfinder';
export default async function getPort(userPort) { export default async function getPort(defaultPort) {
const defaultPort = process.env.PORT || userPort;
return portfinder.getPortPromise({ return portfinder.getPortPromise({
port: defaultPort ? parseInt(String(defaultPort), 10) : 8000, port: defaultPort ? parseInt(String(defaultPort), 10) : 8000,
}); });