webpack 4 + mockjs

1. Create a project directory

2. Add development dependencies (html-webpack-plugin, webpack, webpack-cli, webpack-dev-server, webpack-api-mocker)

in the package.json file as shown below

...
"devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.6.0",
    "webpack-cli": "^2.0.15",
    "webpack-dev-server": "^3.1.3",
    "webpack-api-mocker": "^1.4.3"
  },
...

Use npm install or yarn install (recommended, for reasons you know)

3. Create the webpack.config.js file and write the relevant configuration

  

1 const path = require('path' );
 2 const HtmlWebpackPlugin = require('html-webpack-plugin' );
 3 const apiMocker = require('webpack-api-mocker' );
 4  
5 module.exports = {
 6      mode : 'development', // Current environment 
7      entry: { // Program startup entry 
8          app: './src/index.js'
 9      },
 10      devServer: {
 11          /* ********* ******There are many stars here, pay attention to here ************************* */ 
12          // Using webpack- The before method of dev-server calls webpack-api-mocker
13          // './mocker/index.js' in path.resolve('./mocker/index.js') is the relative path of the mock file 
14          /* ************* *The above is just a simple personal understanding (please communicate if you have different understandings) ***************** */ 
15          before(app) {
 16              apiMocker(app, path.resolve(' ./mocker/index.js' ), ​​{
 17                  // 'GET /api/users/list': 'http://localhost:3000', 
18                  // 'GET /api/userinfo/:id': 'http ://localhost:3000', 
19              })
 20          }
 21      },
 22      output: { // Configuration file output path 
23          filename: '[name].bundle.js' ,
24         path: path.resolve(__dirname, 'dist' )
 25      },
 26      plugins: [ // Generate .html using template files 
27          new HtmlWebpackPlugin({
 28              title: 'webpack+react' ,
 29              template: "./src/entry .ejs" ,
 30              filename: "./index.html" ,
 31          }),
 32      ]
 33 };

Not much to say, go directly to the './mocker/index.js' file

 1 module.exports = {
 2     [`GET /api/user`]: (req, res) => {
 3         console.log('---->', req.params);
 4         return res.json({
 5             id: 1,
 6             username: 'kenny',
 7             sex: 6
 8         });
 9     }
10 }

Appendix 1.

  entry.ejs file in webpack.config.js

  

1  <! DOCTYPE html > 
2  < html lang ="en" > 
3  
4  < head > 
5      < meta http-equiv ="Content-type" content ="text/html; charset=utf-8"  /> 
6      <! -- look here, look here, look at me here --> 
7      < title > 
8          <% = htmlWebpackPlugin.options.title %> 
9      </ title > 
10      <!-- if not write html-webpack-plugin like this The title in is not valid -->
11     <link rel="stylesheet" href="/favicon.png" type="text/css" />
12 </head>
13 
14 <body>
15     <!-- <div id="root"></div> -->
16     Visit :/mocker/index.js to customize the API Try it?
17     <hr>
18     <div>name:
19         <span id="name"></span>
20     </div>
21     <div>age:
22         <span id="age"></span>
23     </div>
24 </body>
25 
26 </html>

  The index.js file of the corresponding value of the app under the entry in the webpack.config.js configuration file

 1 fetch('/api/user', {
 2         'Accept': 'application/json',
 3         'Content-Type': 'application/x-www-form-urlencoded',
 4     })
 5     .then((response) => response.json())
 6     .then(data => {
 7         console.log('data:', data);
 8         document.getElementById('name').innerHTML = data.username;
 9         document.getElementById('age').innerHTML = data.sex;
10     })

 

OK! Next, run npm start or yarn install and try it.

The effect diagram is as follows:

 

Thinking refactoring : Do you need to change the webpack.config.js file when there are multiple mock files in the above method? I will never allow this kind of thing. Visitors please see:

  Solution: write the webpack.mocker.js file as the assembly of all mock files, and automatically package the mock at startup (not much to say, go directly to the code)

1 const mock = {};
2 
3 require('fs').readdirSync(require('path').join(__dirname + '/mocker')).forEach(function (file) {
4     Object.assign(mock, require('./mocker/' + file))
5 });
6 module.exports = mock;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325069541&siteId=291194637