Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix mock don't work and support mock files hot reload #142

Merged
merged 2 commits into from
Feb 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/func-test/.umirc.mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export default {
'/api/hello'(req, res) {
res.end(`hello ${Math.random()}`);
},
...require('./mock/user'),
};
5 changes: 5 additions & 0 deletions examples/func-test/mock/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
'/api/users': {
list: [1, 2, 3, 4],
},
};
9 changes: 4 additions & 5 deletions packages/af-webpack/src/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ export default function dev({
onCompileInvalid = noop,
proxy,
openBrowser: openBrowserOpts,
serverConfig: serverConfigOpts = {},
historyApiFallback = {
disableDotRule: true,
},
}) {
if (!webpackConfig) {
throw new Error('必须提供 webpackConfig 配置项');
Expand Down Expand Up @@ -69,9 +71,7 @@ export default function dev({
watchOptions: {
ignored: /node_modules/,
},
historyApiFallback: {
disableDotRule: true,
},
historyApiFallback,
overlay: false,
host: HOST,
proxy,
Expand All @@ -83,7 +83,6 @@ export default function dev({
}
app.use(errorOverlayMiddleware());
},
...serverConfigOpts,
};
const devServer = new WebpackDevServer(compiler, serverConfig);

Expand Down
30 changes: 1 addition & 29 deletions packages/umi-build-dev/src/Service.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,35 +203,7 @@ export default class Service {
proxy: this.webpackRCConfig.proxy || {},
// 支付宝 IDE 里不自动打开浏览器
openBrowser: !process.env.ALIPAY_EDITOR,
serverConfig: {
after: app => {
app.use((req, res, next) => {
if (req.accepts('html')) {
let pageContent = readFileSync(
join(__dirname, '../template/404.html'),
'utf-8',
);
pageContent = pageContent
.replace('<%= PAGES_PATH %>', this.paths.pagesPath)
.replace(
'<%= PAGES_LIST %>',
this.routes
.map(route => {
return `<li><a href="${route.path}">${
route.path
}</a></li>`;
})
.join('\r\n'),
);
res.writeHead(404, { 'Content-Type': 'text/html' });
res.write(pageContent);
res.end();
} else {
next();
}
});
},
},
historyApiFallback: false,
});
}

Expand Down
2 changes: 1 addition & 1 deletion packages/umi-build-dev/src/getPlugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default function(opts = {}) {
'./plugins/hd',
'./plugins/mock',
'./plugins/hash-history',
'./plugins/404',
'./plugins/404', // 404 must after mock
];
const plugins = [
// builtIn 的在最前面
Expand Down
26 changes: 0 additions & 26 deletions packages/umi-build-dev/src/plugins/404.js

This file was deleted.

53 changes: 53 additions & 0 deletions packages/umi-build-dev/src/plugins/404/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { join } from 'path';
import { existsSync, readFileSync } from 'fs';

const EXTNAMES = ['.js', '.jsx', '.ts', '.tsx'];

export default function(api) {
const { paths } = api.service;
const { winPath } = api.utils;

function get404JS() {
for (const extname of EXTNAMES) {
const filePath = winPath(join(paths.absPagesPath, `404${extname}`));
if (existsSync(filePath)) {
return filePath;
}
}
}

api.register('modifyRoutesContent', ({ memo }) => {
const filePath = get404JS();
if (filePath) {
memo.push(` <Route component={require('${filePath}').default} />`);
}
return memo;
});

api.register('beforeServer', ({ args: { devServer } }) => {
function UMI_PLUGIN_404(req, res, next) {
if (req.accepts('html')) {
let pageContent = readFileSync(
join(__dirname, '../../../template/404.html'),
'utf-8',
);
pageContent = pageContent
.replace('<%= PAGES_PATH %>', paths.pagesPath)
.replace(
'<%= PAGES_LIST %>',
api.service.routes
.map(route => {
return `<li><a href="${route.path}">${route.path}</a></li>`;
})
.join('\r\n'),
);
res.writeHead(404, { 'Content-Type': 'text/html' });
res.write(pageContent);
res.end();
} else {
next();
}
}
devServer.use(UMI_PLUGIN_404);
});
}
86 changes: 73 additions & 13 deletions packages/umi-build-dev/src/plugins/mock/HttpMock.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,25 @@ import { existsSync } from 'fs';
import chalk from 'chalk';
import assert from 'assert';
import bodyParser from 'body-parser';
import chokidar from 'chokidar';

function MOCK_START(req, res, next) {
next();
}

function MOCK_END(req, res, next) {
next();
}

class HttpMock {
constructor({ cwd, devServer, api }) {
this.devServer = devServer;
this.api = api;
this.absMockPath = join(cwd, 'mock');
this.configPath = join(cwd, '.umirc.mock.js');
this.api.registerBabel([this.configPath, this.absMockPath]);
this.applyMock();
this.watch();
}

applyMock() {
Expand All @@ -21,13 +32,48 @@ class HttpMock {
}
}

watch() {
const { devServer, api: { utils: { debug } } } = this;
const watcher = chokidar.watch([this.configPath, this.absMockPath], {
ignoreInitial: true,
});
watcher.on('all', (event, file) => {
debug(`[${event}] ${file}`);
this.deleteRoutes();
this.applyMock();
});
}

/**
* Delete from MOCK_START to MOCK_END
*/
deleteRoutes() {
const { devServer, api: { utils: { debug } } } = this;
const { app } = devServer;
let startIndex = null;
let endIndex = null;
app._router.stack.forEach((item, index) => {
if (item.name === 'MOCK_START') startIndex = index;
if (item.name === 'MOCK_END') endIndex = index;
});
if (startIndex !== null && endIndex !== null) {
app._router.stack.splice(startIndex, endIndex - startIndex + 1);
}
debug(
`routes after changed: ${app._router.stack
.map(item => item.name || 'undefined name')
.join(', ')}`,
);
}

realApplyMock() {
const { debug } = this.api.utils;
const config = this.getConfig();
debug(`config: ${JSON.stringify(config)}`);
const { devServer } = this;
const { app } = devServer;

devServer.use(MOCK_START);
devServer.use(bodyParser.json({ limit: '5mb', strict: false }));
devServer.use(
bodyParser.urlencoded({
Expand All @@ -50,22 +96,31 @@ class HttpMock {
this.createMockHandler(keyParsed.method, keyParsed.path, config[key]),
);
});
devServer.use(MOCK_END);

// 调整 stack,把 historyApiFallback 放到最后
let lastIndex = null;
// 调整 stack,把 UMI_PLUGIN_404 放到最后
let umiPlugin404Index = null;
let endIndex = null;
app._router.stack.forEach((item, index) => {
if (item.name === 'webpackDevMiddleware') {
lastIndex = index;
}
if (item.name === 'UMI_PLUGIN_404') umiPlugin404Index = index;
if (item.name === 'MOCK_END') endIndex = index;
});
// const mockAPILength = app._router.stack.length - 1 - lastIndex;
if (lastIndex && lastIndex > 0) {
const newStack = app._router.stack;
newStack.push(newStack[lastIndex - 1]);
newStack.push(newStack[lastIndex]);
newStack.splice(lastIndex - 1, 2);
app._router.stack = newStack;
if (
umiPlugin404Index !== null &&
endIndex !== null &&
umiPlugin404Index < endIndex
) {
const umiPlugin404Middleware = app._router.stack.splice(
umiPlugin404Index,
1,
);
app._router.stack.push(umiPlugin404Middleware[0]);
}
debug(
`routes after resort: ${app._router.stack
.map(item => item.name || 'undefined name')
.join(', ')}`,
);
}

createMockHandler(method, path, value) {
Expand All @@ -92,7 +147,12 @@ class HttpMock {

getConfig() {
if (existsSync(this.configPath)) {
this.api.registerBabel([this.configPath, this.absMockPath]);
// disable require cache
Object.keys(require.cache).forEach(file => {
if (file === this.configPath || file.indexOf(this.absMockPath) > -1) {
delete require.cache[file];
}
});
return require(this.configPath); // eslint-disable-line
} else {
return {};
Expand Down