mock-delete-loader

A low-risk mock specification and tool

Github address: github.com/gt-Lee/mock…

background

In development, it’s not uncommon for a team member to accidentally forget to remove mock code and post mock data online before release. It’s dangerous, but it’s common. There are reasons why mocks are not standard, and there are also reasons why code reviews are not strict.

But relying on code reviews as a last line of defense to avoid problems can be costly in terms of human and efficiency. So we pioneered the idea of combing and blocking, providing a simple specification and webpack Loader that automatically removes mock code when specifying environment packaging.

The installation

$ yarn add -D mock-delete-loader
Copy the code

Configure the loader

// webpack.conf.js

module.exports = {
// ...
  module: {
    rules: [
      // ...
      {
          test: /\.js$/,
          include: [resolve('src')].use: [
            'babel-loader',
            {
              loader: 'mock-delete-loader'.options: {
                // includeMode specifies the packaging environment in which to delete mock data. If not, default: ['production']
                includeMode: ['production'],}}],},]}}Copy the code

The options that

  • IncludeMode specifies the packaging environment in which the mock data is to be removed, receiving an array of elements corresponding to the Webpack mode. The default value is['production']

Use mocks in code

  • Use in code// #mock// #endWrap the mock code block
  • Write mock data using variable reassignment. Use mock data to overwrite real data rather than changing the original code
// index.js
let numberA = Api.getNumberA()  

// #mock
  numberA = 12 // Wrap the mock code with the specified identity
// #end

console.log(numberA) // The development environment prints 12, and the production environment prints the data returned by the Api

Copy the code

Tips: No Spaces between # and mock or end in the package identifier