Skip to content

Commit

Permalink
feat(umi-build-dev): load files in mock/ automatically if .umirc.mock…
Browse files Browse the repository at this point in the history
….js don't exists (#260)
  • Loading branch information
sorrycc committed Mar 26, 2018
1 parent e31ce03 commit 733f228
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 14 deletions.
2 changes: 1 addition & 1 deletion examples/func-test/.umirc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default {
['./plugin2', 'hihi'],
// 'umi-plugin-yunfengdie',
],
// hd: 1,
hd: 1,
loading: './PageLoadingComponent',
// disableServiceWorker: true,
// exportStatic: {
Expand Down
6 changes: 0 additions & 6 deletions examples/func-test/.umirc.mock.js

This file was deleted.

3 changes: 3 additions & 0 deletions examples/func-test/mock/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ export default {
'/api/users': {
list: [1, 2, 3, 4],
},
'/api/users2': {
list: [1, 2, 3, 4],
},
};
33 changes: 26 additions & 7 deletions packages/umi-build-dev/src/plugins/mock/HttpMock.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import chalk from 'chalk';
import assert from 'assert';
import bodyParser from 'body-parser';
import chokidar from 'chokidar';
import glob from 'glob';

function MOCK_START(req, res, next) {
next();
Expand Down Expand Up @@ -33,7 +34,7 @@ class HttpMock {
}

watch() {
const { devServer, api: { utils: { debug } } } = this;
const { api: { utils: { debug } } } = this;
const watcher = chokidar.watch([this.configPath, this.absMockPath], {
ignoreInitial: true,
});
Expand Down Expand Up @@ -145,15 +146,33 @@ class HttpMock {
return { method, path };
}

disableRequireCache() {
Object.keys(require.cache).forEach(file => {
if (file === this.configPath || file.indexOf(this.absMockPath) > -1) {
delete require.cache[file];
}
});
}

getConfig() {
const { debug } = this.api.utils;

if (existsSync(this.configPath)) {
// disable require cache
Object.keys(require.cache).forEach(file => {
if (file === this.configPath || file.indexOf(this.absMockPath) > -1) {
delete require.cache[file];
}
});
this.disableRequireCache();
return require(this.configPath); // eslint-disable-line
} else if (existsSync(this.absMockPath)) {
this.disableRequireCache();
const mockFiles = glob.sync('**/*.js', {
cwd: this.absMockPath,
});
debug(`mockFiles: ${JSON.stringify(mockFiles)}`);
return mockFiles.reduce((memo, mockFile) => {
memo = {
...memo,
...require(join(this.absMockPath, mockFile)),
};
return memo;
}, {});
} else {
return {};
}
Expand Down

0 comments on commit 733f228

Please sign in to comment.