Commit 49b21124 authored by huanglu's avatar huanglu

mock, proxy

parent ec13a77a
WE_APPID = ''
BASEURL = ''
\ No newline at end of file
WE_APPID = ''
BASEURL = ''
\ No newline at end of file
WE_APPID = ''
BASEURL = ''
\ No newline at end of file
const child_process = require('child_process'); const child_process = require('child_process');
// 监听model文件的修改,并自动注入
const wacthProcess = child_process.fork('build/watch.js', { const wacthProcess = child_process.fork('build/watch.js', {
cwd: process.cwd(), cwd: process.cwd(),
stdio: 'inherit', stdio: 'inherit',
}) })
// 开启dev编译
const devProcess = child_process.spawn('npm', ['run', 'dev:weapp'], { const devProcess = child_process.spawn('npm', ['run', 'dev:weapp'], {
cwd: process.cwd(), cwd: process.cwd(),
stdio: 'inherit' stdio: 'inherit'
}) })
// 开启 mock 服务器
const mockProcess = child_process.fork('build/server.js', {
cwd: process.cwd(),
stdio: 'inherit'
})
devProcess.on('close', () => { devProcess.on('close', () => {
process.exit(0) process.exit(0)
}) })
\ No newline at end of file
...@@ -4,7 +4,7 @@ const render = require("json-templater/string"); ...@@ -4,7 +4,7 @@ const render = require("json-templater/string");
const endOfLine = require("os").EOL; const endOfLine = require("os").EOL;
const fs = require("fs"); const fs = require("fs");
const MODEL_OUTPUT_PATH = resolve("src/models/index.ts"); const MODEL_OUTPUT_PATH = path.join(process.cwd(), "src/models/index.ts");
const IMPORT_TEMPLATE = 'import {{name}} from "{{path}}";'; const IMPORT_TEMPLATE = 'import {{name}} from "{{path}}";';
const MODEL_INDEX_TEMPLATE = `/* Auto import */ const MODEL_INDEX_TEMPLATE = `/* Auto import */
{{imports}} {{imports}}
......
const chalk = require("chalk");
const express = require("express");
const path = require("path");
const mocks = require( path.join( process.cwd(), "mock"));
const { createProxyMiddleware } = require("http-proxy-middleware");
const buildConfig = require(path.join(process.cwd(), "config/build.js"));
const proxy = buildConfig['proxy'] || {}
const { host = 'localhost', port = 8081 } = buildConfig['devServer'] || {}
function startApp(host = 'localhost', port = '8081') {
try {
const app = express();
const rawArgv = process.argv.slice(2);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 配置代理
Object.keys(proxy).forEach((key) => {
app.use(
key,
createProxyMiddleware({
...proxy[key],
})
);
});
Object.keys(mocks).forEach((key) => {
const pathConfig = mocks[key];
Object.keys(pathConfig).forEach((api) => {
configModuleMock(app, key, api, pathConfig[api]);
});
});
app.listen(port, host, (err) => {
if (!err) {
console.log(`mock server listen on ${chalk.cyan(`${host}:${port}`)}`);
}
});
} catch (e) {
console.log(e);
}
}
function configModuleMock(app, module, path, config) {
const isPost = /^POST/g.test(path);
const apiPath = path.replace(/POST /g, "").replace(/GET /g, "");
console.log(module, apiPath, config, isPost);
const router = express.Router();
if (isPost) {
router.post(apiPath, (req, res, next) => {
console.log("post: ", req, res);
res.status(200);
return typeof config === "function" ? config(req, res, next) : config;
});
} else {
router.get(apiPath, (req, res) => {
console.log("get: ", req, res);
res.status(200);
return typeof config === "function" ? config(req, res) : config;
});
}
app.use(`/${module}`, router);
}
console.log(chalk.blue('开启mock服务器...'))
startApp(host, port)
\ No newline at end of file
...@@ -8,7 +8,7 @@ const resolve = (dir) => { ...@@ -8,7 +8,7 @@ const resolve = (dir) => {
} }
const configPath = (pth) => { const configPath = (pth) => {
const dstFile = pth.split('src')[1].slice(1) const dstFile = pth.split('src')[1].slice(1).replace(/\.(js|ts)$/g, '')
return `@/${dstFile}` return `@/${dstFile}`
} }
...@@ -26,8 +26,8 @@ const formatFile = (pth) => { ...@@ -26,8 +26,8 @@ const formatFile = (pth) => {
} }
const searchModels = () => { const searchModels = () => {
const { found : models } = glob.GlobSync(resolve('src/**/*model.ts')) const { found : models } = glob.GlobSync(path.join(process.cwd(), 'src/**/*model.ts'))
const { found : subModels } = glob.GlobSync(resolve('src/models/*.ts')) const { found : subModels } = glob.GlobSync(path.join(process.cwd(), 'src/models/*.ts'))
const modelsPath = [ const modelsPath = [
...models, ...models,
...subModels ...subModels
......
const fs = require('fs') const fs = require('fs')
const chalk = require('chalk')
const { autoInjectModels } = require('./models') const { autoInjectModels } = require('./models')
const { resolve } = require('./util') const { resolve } = require('./util')
console.log('正在监听文件修改...') console.log(chalk.blueBright('正在监听文件修改...'))
fs.watch(resolve('src'), { persistent: true, interval: 5 , recursive: true }, (curr, filename) => { fs.watch(resolve('src'), { persistent: true, interval: 5 , recursive: true }, (curr, filename) => {
if ((filename || '').indexOf('model') != -1) { if ((filename || '').indexOf('model') != -1) {
if (/\/(index.ts)$/g.test(filename)) { if (/\/(index.ts)$/g.test(filename)) {
return; return;
} }
console.log(`${filename}文件已修改...`) console.log(chalk.cyanBright(`${filename}文件已修改...`))
autoInjectModels() autoInjectModels()
} }
}) })
......
module.exports = {
proxy: {
"/service-profile": {
target: "http://192.168.32.35:3000/", //process.env.SERVER_ENDPOINT,
logLevel: "debug",
changeOrigoin: true,
},
},
// 目前只支持 host, port 的相关配置
devServer: {
host: 'localhost',
port: 9000
}
};
...@@ -79,7 +79,15 @@ const config = { ...@@ -79,7 +79,15 @@ const config = {
} }
} }
} }
} },
geekProxy: {
"/service-profile": {
target: "http://192.168.32.35:3000/", //process.env.SERVER_ENDPOINT,
logLevel: "debug",
changeOrigoin: true,
},
},
proType: 'taro'
} }
module.exports = function (merge) { module.exports = function (merge) {
......
module.exports = {
'/addCart': (req, res, next) => {
res.json({
code: 0,
message: 'sssfsff'
})
}
}
\ No newline at end of file
const cart = require('./cart')
module.exports = {
user: {
'GET /login':() => {
return {
name: 'huanglu'
}
},
'POST /dd':() => {
return {
name: 'huanglu'
}
}
},
common: {
'GET /config': {
version: '1.1.10'
}
},
cart
}
\ No newline at end of file
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
"typescript": true, "typescript": true,
"css": "sass" "css": "sass"
}, },
"miniPrograme": true,
"scripts": { "scripts": {
"build:weapp": "taro build --type weapp", "build:weapp": "taro build --type weapp",
"build:swan": "taro build --type swan", "build:swan": "taro build --type swan",
...@@ -66,12 +67,15 @@ ...@@ -66,12 +67,15 @@
"babel-plugin-transform-object-rest-spread": "^6.26.0", "babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-runtime": "^6.23.0", "babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1", "babel-preset-env": "^1.6.1",
"chalk": "^4.0.0",
"eslint": "^5.16.0", "eslint": "^5.16.0",
"eslint-config-taro": "2.2.3", "eslint-config-taro": "2.2.3",
"eslint-plugin-import": "^2.12.0", "eslint-plugin-import": "^2.12.0",
"eslint-plugin-react": "^7.8.2", "eslint-plugin-react": "^7.8.2",
"eslint-plugin-react-hooks": "^1.6.1", "eslint-plugin-react-hooks": "^1.6.1",
"eslint-plugin-taro": "2.2.3", "eslint-plugin-taro": "2.2.3",
"express": "^4.17.1",
"http-proxy-middleware": "^1.0.3",
"json-templater": "^1.2.0", "json-templater": "^1.2.0",
"stylelint": "9.3.0", "stylelint": "9.3.0",
"stylelint-config-taro-rn": "2.2.3", "stylelint-config-taro-rn": "2.2.3",
......
/* Auto import */ /* Auto import */
import home from "@/pages/home/model.ts"; import home from "@/pages/home/model";
import common from "@/models/common.ts"; import index from "@/pages/index/model";
import common from "@/models/common";
export default [ export default [
home, home,
index,
common, common,
] ]
export default <DvaModel<any>> {
namespace: 'index',
state: {
age: 23,
name: ''
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment