demand
The contents of a js file are as follows
(function getApis() { return {}; }) ();Copy the code
The request from the client is as follows
"/api/page2"
Copy the code
Here’s what your mock will automatically generate
(function getApis() { return { "/api/page2": { body: { status: 200, data: {}, }, }, }; }) ();Copy the code
Reduce the cost of copy and paste
To measure
GetApis () {return () {return () {return () {return () {return ()
implementation
CNPM install — save-dev@babel /parser
const babelParser = require("@babel/parser"); const ast = babelParser.parse(` (function getApis() { return {}; }) (); `);Copy the code
It is important to find an online site to watch structure, such as :astexplorer.net/
Traverse node CNPM install — save-dev@babel /traverse
const { default: babelTraverse } = require("@babel/traverse"); let pos = null; babelTraverse(ast, { FunctionExpression(path) { if (path.node.id.name === "getApis") { pos = path.node.body.body[0].argument.start + 1; path.skip(); }}});Copy the code
How is FunctionExpression determined if the AST is given at the time of output
Path.node.id. name === “getApis” to confirm that this is the function we are looking for pos after its return statement {
@babel/types (prettier, prettier, prettier, prettier, prettier, prettier, prettier, prettier
let content =
mockFileStr.slice(0, pos) +
`
"${params.url}":${JSON.stringify(
params.defaultConfig.autoCreateSettings.getDefaultValues(),
null,
2
)},
` +
mockFileStr.slice(pos);
fs.writeFileSync(
path.resolve(__dirname, moclFilepath),
prettier.format(content)
);
Copy the code
Complete example :github.com/xiaodun/sf-…
touch
I remember being asked a question about Babel in a phone interview, and I just said that I was doing code translation. It was perfuncted. at least I had to tell you what these @babel/core libraries were for