Front-end development data mock artifact--Xl_mock

Source: Internet
Author: User
1, why to achieve data mock

To understand why data mocks are implemented, we can provide several scenarios to explain

1, now the development of many are the front-end separation of the mode, the front and back of the work is different, when our front-end interface has been completed, but the backend interface is slow to provide

The front end will often wait for the interface.

2, testers want you to provide a direct test, self-modification back-end interface, testing the UI.

3, the back end of the interface, can not provide some matching scenes of the time.

At this point, if the front-end can implement their own set of mock data, the problem here will be solved, we can simulate the real interface, provide our own needs and data structure.

In this way, we can complete testing, debugging, and optimization in the event that the backend is not completed.

2. Mock data scheme

When it comes to front-end development, implementing front-end data to mock-up is an essential step in front-end construction, whether in development or debugging.

So what do we do with the mock of the data? One of the most common to methods is the following:

For example:

1, introduce mock.js to achieve request interception.

2, to build a self-to-mock server, simulate their own want to the data and its structure.

3. Build rap visualization to a mock server

4, there are many other special to the means ....

  

In these methods, the simulation data is used to realize the front-end display, improve the front-end development efficiency and development rhythm.

  

Xl_mock Introduction

  Xl_mock is a NPM package that is a visual data mock based on the mock.js development.

It enables you to open a local data mock server through commands in your project.

And the mock data type will exist in the project for co-development.

  

Xl_mock usage and its preview

1, first global installation Xl_mock

NPM install-g Xl_mock

Global commands can be implemented in a global installation.

If not installed in the project project, a global mock server is turned on. This is not advisable.

2. Add NPM package Xl_mock to the project

Yarn Add Xl_mock

  

Add Xl_mock to the project so that when the service is opened it will only take effect on the current project.

3. Open the mock server in the project

Xl_mock start-p 2048

  

This opens the mock server for the project, and the listening port is good for 2048.

If the port number is occupied, the process of the port number is stopped first and then reopened.

First, a mock directory is generated at the root of the project to hold the data. (Not regenerated if a mock directory exists)

You can see that a local server is turned on and the http://127.0.0.1:2014/index.html

What we see here is a visualization, interface additions, interface modifications, and interface type additions.

4. Add an interface

A uesrinfo interface has been added here

And the request address is/get/userinfo

You can also choose the method, the description of the interface, and the interface specific information.

When we click Submit data, the interface information has been written to the mock folder in the local project directory for extraction.

5. Interface verification and invocation

Here, I am directly entering the interface address into the browser to verify that the interface is in effect.

So in the project, how do we call it?

We can determine a mock environment and replace the request address with http://127.0.0.0:2048, which implements the invocation of the interface.

Xl_mock with respect to other advantages:

Relative to Mock.js:

Xl_mock has been proposed from the project and does not require interface request interception, so that development is closer to the backend interface

Xl_mock provides a visual interface so that interface browsing is more intuitive

  

Relative to the general mock server:

No need to build mock servers specifically

Here, we can more conveniently, more concise to complete a mock function

project is still in the development and improvement, if we feel that there is any bug or what unreasonable position, heartily put forward, as soon as possible to optimize and modify ...

  

Blog: NPM tools--mock Server (Xl_mock)

3, Development xl_mock knowledge carding

    

What does it take to develop a xl_mock NPM package?

Here's a list of the basic items:

1, Mock.js mock.js Basic use method

2. Create your own NPM package

3, node's knowledge is mainly command-line tools

4, the introduction of Mock.js

Here I will briefly introduce the mock.js, specifically want to know can visit the official website

Mock.js official website

Mock.js Installation

Common Direct Introduction:

Introducing  <script src= "http://mockjs.com/dist/mock.js" directly into HTML ></script>;

  

Installation in modular form

Installation: NPM install MOCKJS--save-devyarn Add mockjs

  

  

Mock.js How to implement mock data:

Mock.mock (template) Mock.mock (rurl,function (options)) Mock.mock (rurl,rtype,template) mock.mock (Rurl,rtype, function (options))

    • Template represents the template of the data, Mock.mock (template) Here, the data and its structure are returned according to the template

    • Rurl Mock.js can intercept the request, here is the address to intercept, after intercepting the address, according to the function or template to return the required data

    • Rtype This is the type of interception request

    • function here represents the function that generates the data, which can be more intuitive

  

A brief introduction to the Mock.js template

Rules for defining data templates:

Each property in the data template consists of 3 parts: the name of the property, the rule that generated the value, and the property value

' Name|rule ': Value property name | The rule that generated the value: property value

  

The definition of a placeholder:

A placeholder is a string that is written with @ at the location of the property value and does not appear in the final data, but in a data format

Format:

@ placeholder @ placeholder (parameters [, parameters])

  

Example:

{     name: ' @cname ',
   City: ' @city (True) '}

The generated data

{Name     : ' Chinese name ',   City: ' Chinese Cities '}

  

Mock.js in the tool set

There are placeholders in the data template, and the corresponding Mock.random toolset also enables the generation of various data

For example:

Ar Random = mock.random; Random.email ()       ///function generation data in Random       //= "long.xiao@qq.com" Mock.mock (' @EMAIL ')  //Mock function for generating data//= "Xiao.da@gil.org"

  

To create a finished template:

{    "users|1-2": [{   //randomly generate 1 to 2 array elements        ' name ': ' @cname ',//  Chinese name        ' id|+1 ': 108,    //attribute value Auto plus 1, initial value 108 '        birthday ': ' @date ("yyyy-mm-dd") ',  //Date        ' city ': ' @city (True) ',   //Chinese Cities         }]}

  

The generated data:

{users:[{name: ' Xiaol ', id:1, Birthday: ' 2018-09-12 ', City: ' Beijing '}, {name: ' Dal ', Id:2, BIRTHD Ay: ' 2014-09-12 ', City: ' Shanghai '},]}

  

The basic operations and functions of Mock.js are described here.

Learn more about mock.js you can go to the official web site to browse the next 5, create your own NPM package

To create your own NPM package, start by knowing if you create a

Here's a simple example: how to develop a NPM package of your own

1, modify the Package.json

{  "name": "Xl_mock",  "version": "1.0.5", "  description": "For creating a mock, creating a mock service, generating a mock directory ...", "  Main": " Index.js ",  " scripts ": {    " test ":" Echo \ "Error:no test specified\" && exit 1 "  },   //main modification, add command properties c8/> "Bin": "./bin/xl_mock.js",  "author": "Xiaolong",  "license": "ISC",  "dependencies": {    " Body-parser ":" ^1.18.3 ",    " chalk ":" ^2.4.1 ",    " Commander ":" ^2.17.1 ",    " Ejs ":" ^2.6.1 ",    " Express " : "^4.16.3",    "express-session": "^1.15.6", "    Forever": "^0.15.3",    "KP": "^1.1.2",    "mockjs": "^ 1.0.1-beta3 ",    " OPN ":" ^5.3.0 ",    " Shelljs ":" ^0.8.2 ",    " Yargs ":" ^12.0.1 "  }}

  

Add our command entry./bin/xl_mock.js

2. Command Entry file modification

#!/usr/bin/env node//  is mainly to add a language resolution in the first line//  this tells the system to parse the file with node

  

A brief introduction to the main two points of NPM development

If you need a more detailed understanding of NPM package development.

You can browse through this simple tutorial: How to develop a NPM package of your own

or browse official website: NPM website

3. Node related tools and knowledge

NPM is based on node, so our essential knowledge is the knowledge of node.

such as node-to-File operations module FS, node process management processes, subprocess child_precess

There are several command-line tools:

Chalk

Chalk is a color plug-in. You can change the color by chalk.blue (' Hello World '),

  

Const CHALK = require (' chalk '); const LOG = console.log;//Changes the color of the text on the command line//This will print the blue Hello worldlog (' Hello Chalk.blue ' ');//print Blue Hello  and red! Log (Chalk.blue (' Hello ') + ' world ' + chalk.red ('! '));

  

This tool can improve the command line appearance when we operate the command.

Commander

The commander is a lightweight Nodejs module that provides user command line input and parameter parsing power.

This tool is primarily used to implement user interaction in commands.

Features of the Commander:

Record code, generate help document

Combine short parameters, record parameters

Implement various options

Parse the command and save

Simple command Prompt

 Commander's API:

    • Option (): Initialize the custom Parameter object, set the "keywords" and "description"

    • Command (): Initialize the commands line parameter object and get the command line input directly

    • Command#command (): Define a command name

    • Command#action (): Register a callback function

    • Command#option (): Define the parameters, you need to set "keyword" and "description", the keyword includes "shorthand" and "full write" two parts, with ",", "|", "space" to do the separation.

    • Command#parse (): Parse command-line arguments argv

    • Command#description (): Set description value

    • Command#usage (): Set usage value

  

Case:

Program    . Version (Package.version)    . Usage (' [cmd] [options] '). Option ('    -P ', ' Configure Port number ')    . Option ('-d ', ' Configure the mock directory name, default mock ')    . Option ('-X ', ' Set password ')

Create a STRT command (' Start ') . Description (' Turn on Mock server: '). Action (path, options) = { start (argv) }) Program . Command (' Add <path> ') . Description (' Add mock data: ') . Action (path) = { opn (' http://127.0.0.1:${port}/index.html ', {app: ' Google Chrome '); }) Program.parse (PROCESS.ARGV)

  

You can do this at the command line:

Xl_mock Start Options

  

The corresponding action in the start command will be executed here

There's a lot of useful command lines and node related NPM packages

Node Toolkit: Node Tool-NPM Package

  

4. Brief introduction of the project

Code development and process, here is a brief introduction to knowledge.

If you want to know more, you can browse my original code and post a GitHub address later.

Browse the project introduction when the best control of the source to see: source GitHub

Entry file:

There are two main functions: one is start to open the mock server, and the other is to add API interface

Turn on the mock server

program    .version(package.version)    .usage('[cmd] [options]')    .option('-p', '配置端口号')    .option('-d', '配置mock目录名称 ,默认 mock')program    .command('start')    .description('开启mock服务器..')    .action((path, options) => {        start(argv)   // 调用服务文件开发 服务器})

Open browser Add API interface page

program.command('add <path>').description('添加 mock 数据..').action((path) => {    opn(`http://127.0.0.1:${port}/index.html`,{app: 'google chrome'});})

To start the mock server file:

Steps:

1. Copy the necessary template files into the project directory mock folder

So you don't lose the mock data.

2, Development Server, if the port is used to kill the port process, re-open

Server files:

Main functions:

1. Home page for adding/displaying interfaces and their interface classifications

2, add interface classification interface

3. Get the interface under a category

4. Add interface

5. Get interface Information

6, according to obtain the address to be inverted mock data

Home code:

The Ejs template engine used here displays a list of all interfaces under classification and default classification

To add a classification code:

Main functions:

Add Category

1. Save the classification information in the./data/index.json file.

2. Create a classification JSON to be used to add the API interface under this category to provide

Get the classification code:

Main functions:

1, get the data under the Index.json

2. Get the API data list of the corresponding classification API JSON

Add API Interface Code:

Main functions:

1, add the interface to the corresponding classification into the API JSON, easy to invoke and mock data

2, add the interface information to the Index.json, in the mock call time, quickly to locate the mock template

Get API Data/Get mock data code:

Here is mainly the most important:

The input data is converted to mock data, which is mainly the Getmockdata method.

5. Xl_mock Usage

1. Global Installation

NPM install-g Xl_mock

2. Project Installation Dependent

Yarn Add Xl_mock

3. Turn on the mock server

Xl_mock Start-p 3000

4. Access Address http://127.0.0.0:3000/index.html

Project directory

Code has just been developed, if there are deficiencies or suggestions please leave a message to discuss ....

  

Blog Park summary baba: www.cnblogs.com/jiebba/p/9596707.html xiaolong ' s blog

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.