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) => {
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);
const hostname = getHostName(api.config.viteOption.server?.host);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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