From 443879bf4ffed6a827c829da33aaef39960db795 Mon Sep 17 00:00:00 2001 From: wanchun <445436867@qq.com> Date: Fri, 6 May 2022 13:10:09 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E4=B8=80=E4=BA=9Bbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/commands/dev/getDevConfig.js | 2 +- .../fes-build-vite/src/commands/dev/index.js | 2 +- .../src/plugins/commands/dev/devServer.js | 10 +-- .../src/plugins/commands/dev/index.js | 17 ++-- packages/fes-compiler/src/logger/index.js | 13 +-- .../src/plugins/registerMethods.js | 3 - .../src/plugins/watch/watchMode.js | 8 +- packages/fes-template/mock.js | 87 +++++++++++-------- packages/fes-utils/src/getPort.js | 3 +- 9 files changed, 74 insertions(+), 71 deletions(-) diff --git a/packages/fes-build-vite/src/commands/dev/getDevConfig.js b/packages/fes-build-vite/src/commands/dev/getDevConfig.js index c5903994..5f5222ce 100644 --- a/packages/fes-build-vite/src/commands/dev/getDevConfig.js +++ b/packages/fes-build-vite/src/commands/dev/getDevConfig.js @@ -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); diff --git a/packages/fes-build-vite/src/commands/dev/index.js b/packages/fes-build-vite/src/commands/dev/index.js index 1f4be423..660a27d4 100644 --- a/packages/fes-build-vite/src/commands/dev/index.js +++ b/packages/fes-build-vite/src/commands/dev/index.js @@ -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(); diff --git a/packages/fes-build-webpack/src/plugins/commands/dev/devServer.js b/packages/fes-build-webpack/src/plugins/commands/dev/devServer.js index 75af1c91..f3fc619a 100644 --- a/packages/fes-build-webpack/src/plugins/commands/dev/devServer.js +++ b/packages/fes-build-webpack/src/plugins/commands/dev/devServer.js @@ -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; } diff --git a/packages/fes-build-webpack/src/plugins/commands/dev/index.js b/packages/fes-build-webpack/src/plugins/commands/dev/index.js index 52f1f8cd..5e4fd7e8 100644 --- a/packages/fes-build-webpack/src/plugins/commands/dev/index.js +++ b/packages/fes-build-webpack/src/plugins/commands/dev/index.js @@ -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', diff --git a/packages/fes-compiler/src/logger/index.js b/packages/fes-compiler/src/logger/index.js index dff4fd39..b8234227 100644 --- a/packages/fes-compiler/src/logger/index.js +++ b/packages/fes-compiler/src/logger/index.js @@ -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 || ''}`; diff --git a/packages/fes-preset-built-in/src/plugins/registerMethods.js b/packages/fes-preset-built-in/src/plugins/registerMethods.js index 98a336d6..cabaa66f 100644 --- a/packages/fes-preset-built-in/src/plugins/registerMethods.js +++ b/packages/fes-preset-built-in/src/plugins/registerMethods.js @@ -16,11 +16,8 @@ export default function (api) { 'addEntryCodeAhead', 'addEntryCode', 'modifyRoutes', - 'addConfigType', - 'addTmpGenerateWatcherPaths', - 'addBeforeMiddlewares', 'addMiddlewares', ].forEach((name) => { diff --git a/packages/fes-preset-built-in/src/plugins/watch/watchMode.js b/packages/fes-preset-built-in/src/plugins/watch/watchMode.js index 14aa30b4..92d6c177 100644 --- a/packages/fes-preset-built-in/src/plugins/watch/watchMode.js +++ b/packages/fes-preset-built-in/src/plugins/watch/watchMode.js @@ -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(); diff --git a/packages/fes-template/mock.js b/packages/fes-template/mock.js index df5a9d88..3499d487 100644 --- a/packages/fes-template/mock.js +++ b/packages/fes-template/mock.js @@ -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: '文件上传成功', }); }); } diff --git a/packages/fes-utils/src/getPort.js b/packages/fes-utils/src/getPort.js index 3d622ebe..e7b3c6a0 100644 --- a/packages/fes-utils/src/getPort.js +++ b/packages/fes-utils/src/getPort.js @@ -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, });