Skip to content

Commit 2b357d3

Browse files
committed
refactor(mock): 同步 mock 代码
1 parent 4c08ffc commit 2b357d3

File tree

2 files changed

+18
-13
lines changed

2 files changed

+18
-13
lines changed

mock/mockServer.ts

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
const chokidar = require('chokidar');
22
const bodyParser = require('body-parser');
33
const chalk = require('chalk');
4+
const path = require('path');
5+
6+
const mockDir = path.join(process.cwd(), 'mock');
47

58
function registerRoutes(app) {
69
let mockLastIndex;
@@ -18,15 +21,15 @@ function registerRoutes(app) {
1821

1922
function unregisterRoutes() {
2023
Object.keys(require.cache).forEach((i) => {
21-
if (i.includes('/mock')) {
24+
if (i.includes(mockDir)) {
2225
delete require.cache[require.resolve(i)];
2326
}
2427
});
2528
}
2629

2730
module.exports = (app) => {
2831
// es6 polyfill
29-
require('@babel/register')({ extensions: [ '.ts', '.tsx', '.js', '.jsx'] });
32+
require('@babel/register')({extensions: ['.ts', '.tsx', '.js', '.jsx']});
3033
// parse app.body
3134
// https://expressjs.com/en/4x/api.html#req.body
3235
app.use(bodyParser.json());
@@ -39,23 +42,26 @@ module.exports = (app) => {
3942
let mockStartIndex = mockRoutes.mockStartIndex;
4043

4144
// watch files, hot reload mock server
42-
chokidar.watch(('./mock'), {
45+
chokidar.watch(mockDir, {
4346
ignored: 'mock/mockServer.ts',
44-
persistent: true,
4547
ignoreInitial: true
4648
}).on('all', (event, path) => {
4749
if (event === 'change' || event === 'add') {
48-
// remove mock routes stack
49-
app._router.stack.splice(mockStartIndex, mockRoutesLength);
50+
try {
51+
// remove mock routes stack
52+
app._router.stack.splice(mockStartIndex, mockRoutesLength);
5053

51-
// clear routes cache
52-
unregisterRoutes();
54+
// clear routes cache
55+
unregisterRoutes();
5356

54-
const mockRoutes = registerRoutes(app);
55-
mockRoutesLength = mockRoutes.mockRoutesLength;
56-
mockStartIndex = mockRoutes.mockStartIndex;
57+
const mockRoutes = registerRoutes(app);
58+
mockRoutesLength = mockRoutes.mockRoutesLength;
59+
mockStartIndex = mockRoutes.mockStartIndex;
5760

58-
console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`));
61+
console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`));
62+
} catch (error) {
63+
console.log(chalk.redBright(error));
64+
}
5965
}
6066
});
6167
};

mock/remoteSearch.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import Mock from 'mockjs';
2-
import { param2Obj } from '@/utils';
32

43
const NameList: any[] = [];
54
const count = 100;

0 commit comments

Comments
 (0)