Code Monkey home page Code Monkey logo

mockjs-webpack-plugin's Introduction

MockjsWebpackPlugin

中文readme

Quickly build mock service for your project as a webpack plugin based on mockjs

What is the problem this plugin solved

Through the way of webpack plugin, we can quickly build a mock service of project for parallel development in front-end and back-end separation mode.

Start up

Install

npm install --save-dev webpack mockjs-webpack-plugin

Config

Add a mock data storage folder in your project.

.
├── app         //project folder
    ├── dist
    ├── config
    ├── src
    ├── mock    //mock data folder
    ⎪   ├── data.js
    ⎪   ├── data.json
        ...

config proxy and mock-webpck-plugin in webpack.config.js

// import plugin
const MockjsWebpackPlugin = require("mockjs-webpack-plugin");

module.exports = {
  entry: "./index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "my-first-webpack.bundle.js"
  },
  // config plugin
  plugins: [
    new MockjsWebpackPlugin({
      // mock data folder path
      path: path.join(__dirname, "./mock"),
      // mock server port, avoid collision with application port
      port: 3000
    })
  ],
  // config proxy
  devServer: {
    // application port
    port: 5001,
    proxy: {
      // mock server url
      "/": "http://localhost:3000/"
    }
  }
};

if you want to set a special url for mock service, you can use webpack proxy like this:

...
module.exports = {
  ...
  // config proxy
  devServer: {
    // application port
    port: 5001,
    proxy: {
      '/api': {
        target: 'http://localhost:3000/',
        pathRewrite: {
          // set url rewrite, for example, 
          // http://localhost:5001/api/getData -> http://localhost:3000/getData
          '^/api': ''
        }
      }
    }
  }
};

When you add a mock data file, do not need to modify the webpack config file but restart the application

OPTIONS

new MockjsWebpackPlugin(options);
  • options.path mock data folder path
  • options.port the port of the mock server, default 3000

Mock Data

Mock Data here is not a real JSON file, and more like a JS file. When we just want to return data without any processing, a json mock file will be proper. So you want to use the following format.

/**
 * Json data file
 *
 * @url /json/data
 *
 * Here you can write a detailed description
 * of the parameters of the information.
 *
 * Parameter description and other instructions.
 * uid: user ID
 * name: username
 * email: the email
 * etc.
 */
{
  "code": 0,
  "result|5": [
    {
      "uid|+1": 1,
      "name": "@name",
      "email": "@email"
    }
  ]
}

You can read the file content like this

  • title: Json data file
  • url: /json/data
  • Description:
Here you can write a detailed description
of the parameters of the information.

Parameter description and other instructions.
 uid: user ID
 name: username
 email: the email
etc.
  • data content: the rest part

Then you can access the http://[localhost]:[3000]/json/data through the browser.

In addition, we can use the JS file directly, which is very useful when we need to check the input parameters.

/**
 * JS data file
 *
 * @url /js/js-data-file
 *
 * Export data by using the JS file directly.
 */

module.exports = {
    "code": function () { // simulation error code, 1/10 probability of error code 1.
        return Math.random() < 0.1 ? 1 : 0;
    },
    "list|5-10": [
        {"title": "@title", "link": "@url"}
    ]
};

Or export function.

/**
 * JS function file
 *
 * @url /js/js-func-file/user?uid=233
 *
 * GET: Request method and parameter
 *   uid This is the requested userID
 *
 * Here you can write a detailed description
 * of the parameters of the information.
 */
module.exports = function(req) {
  var uid = req.query.uid;

  if (!uid) {
    return {
      code: -1,
      msg: "no uid"
    };
  }

  return {
    code: 0,
    data: {
      uid: +uid,
      name: "@name",
      "age|20-30": 1,
      email: "@email",
      date: "@date"
    }
  };
};

All above data comes from mockjs syntax,you can read docs and samples from website of mockjs to get more

mock data desciption comes from 52cik/express-mockjs

Mock JSON

#ChangeLog version 3.0.0 -- 2019.04.07

  1. nothing updated! Just use npm version <update_type> and then i find my package.json has been updated to 3.0.0 version 2.0.0 -- 2019.04.06
  2. support hot reload mock files changes, like add new file or update content.

Support

This repo is coming from MarxJiao/mock-webpack-plugin and 52cik/express-mockjs.

Thanks this two author, Marx(MarxJiao) and 楼教主(52cik)

mockjs-webpack-plugin's People

Contributors

soon08 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

wwwk

mockjs-webpack-plugin's Issues

关于post的支持和js文件加载失败

  1. 好像看server文件中对于app没有使用express.json和esxpress.urlencoded进行post等请求没法正确解析请求体中携带参数。
  2. 目前没找到问题,当使用.js文件进行载入时,require会报错.

TypeError: Cannot read property 'loaded' of null
at Function.Module._load (internal/modules/cjs/loader.js:751:23)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:92:18)
at D:\frontend_project\fed.m-change\node_modules_mockjs-webpack-plugin@3.0.1@mockjs-webpack-plugin\src\routes.js:65:20
at Layer.handle [as handle_request] (D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\layer.js:95:5)
at trim_prefix (D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\index.js:317:13)
at D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\index.js:284:7
at Function.process_params (D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\index.js:335:12)
at next (D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\index.js:275:10)
at urlencodedParser (D:\frontend_project\fed.m-change\node_modules_body-parser@1.19.0@body-parser\lib\types\urlencoded.js:82:7)
at Layer.handle [as handle_request] (D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\layer.js:95:5)
at trim_prefix (D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\index.js:317:13)
at D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\index.js:284:7
at Function.process_params (D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\index.js:335:12)
at next (D:\frontend_project\fed.m-change\node_modules_express@4.17.1@express\lib\router\index.js:275:10)
at D:\frontend_project\fed.m-change\node_modules_body-parser@1.19.0@body-parser\lib\read.js:130:5

模拟接口请求的时候遇到了 504 报错

环境描述:

macOS: 10.12.6
node: v8.7.0
npm: 5.7.1
webpack: ^4.1.1

代码目录结构大概是:

├── dist
├── config
├── src
├── webpack.config.js
├── mock    //mock data folder
⎪   ├── data.js
⎪   ├── data.json

接口报错 504 Gateway Timeout

出错提示显示 from localhost:9000 to http://localhost: 3000/ (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.