npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@tzxhy/vite-generate-mock

v0.0.1

Published

根据 `swagger.json` 文档,创建 `vite-plugin-mock` 所用的 ts 文件。

Readme

@tzxhy/vite-generate-mock

根据 swagger.json 文档,创建 vite-plugin-mock 所用的 ts 文件。

安装

yarn add @tzxhy/vite-generate-mock -D

使用

创建自定义文件,如:

// scripts/generate-mock.js

// 用于生成mock结构
/* eslint-disable */
const path = require('path');
const fs = require('fs');
const generate = require('@tzxhy/vite-generate-mock').default;
let customJsonConf = {};
try {
    customJsonConf = require('../mock/custom-mock-conf');
} catch(e) {
    console.log('如果需要自定义代理,创建 mock/custom-mock-conf.js 文件内容如:' + `
module.exports = {
    '/v1/mec/device/create_sensor': {
        url: '/api/mec/device/create_sensor_new',
        method: 'post',
        response: () => ({
            errCode: 0,
            errMsg: 'success',
            errDetail: Random.string(),
            data: {
                rsuSerial: Random.string(),
            },
        }),
    },
};`);
}

const customInterfaceKeys = Object.keys(customJsonConf);

const mockCodes = generate({
    fileHeader: '',
    // 指定 swagger.json 文件地址
    apiPath: path.join(__dirname, '..', 'swagger', 'api.swagger.json'),
    apiPathRewrite(apiPath) {
        return apiPath.replace('/v1', '/api');
    },
    // api 替换,使用自定义的内容
    apiReplace(apiPath) {
        if (customInterfaceKeys.includes(apiPath)) {
            return this.returnObj(customJsonConf[apiPath]);
        }
    },
    // this 绑定了辅助函数;apiPath为接口地址;curveKeyName为key名称;curveLevel为嵌套级别。从1开始。
    // apiPath 为转换前的path
    responseAdapter(apiPath, curveKeyName, curveLevel) {
        if (curveKeyName === 'totalPages') {
            return this.createNumberLiteral(100);
        }
        if (curveKeyName === 'count') {
            return this.createNumberLiteral(10000);
        }
        if (curveKeyName === 'id') {
            return this.createRandomNumber(1, 1000);
        }
        if (curveKeyName === 'alertingNum'
        || curveKeyName === 'totalAlerting'
        || curveKeyName === 'totalErrors'
        || curveKeyName === 'totalHistoryErrors'
        || curveKeyName === 'totalHistoryAlerting'
        
        ) {
            return this.createRandomNumber(1, 200);
        }
        if (curveKeyName === 'keepingTime') {
            return this.createRandomNumber(1000 * Math.floor(Math.random() * 1e3), 1e8);
        }
        if (curveKeyName === 'timestamp') {
            return this.createStringLiteral(new Date().valueOf() + '')
        }
        if (curveKeyName === 'errCode') {
            return this.createNumberLiteral(0);
        }
        if (curveKeyName === 'errMsg') {
            return this.createStringLiteral('success');
        }
    }
});

// 产物地址
const mockDest = path.join(__dirname, '..', 'mock', 'api.ts');
fs.writeFileSync(mockDest, mockCodes);
console.log('mock源文件已生成至: ' + mockDest);

配置 package.json

{
    "scripts": {
        "start-with-mock": "yarn typings && yarn generate-mock && vite --open --mode mock",
        "generate-mock": "node scripts/generate-mock",
        "typings": "other things"
    }
}

配置 vite.config.js,如下:


import {
    defineConfig,
} from 'vite';

import {
    viteMockServe,
} from 'vite-plugin-mock';

export default defineConfig((env) => {
    const plugins = [];
    if (env.mode === 'mock') {
        console.log('use mock server...');
        // mock plugin
        plugins.push(
            viteMockServe({
                mockPath: 'mock',
                localEnabled: true,
            }),
        );
        // scripts/generate-mock.js 文件地址
        const mockGenerate = path.join(__dirname, 'scripts', 'generate-mock.js');

        // 文件更新,那么重新生成mock数据
        fs.watch(mockGenerate, () => {
            childProcess.exec('node ' + mockGenerate, (err, std) => {
                console.log(std);
            });
        });

        // 自定义文件更新,同样触发更新
        try {
            const customMock = path.join(__dirname, 'mock', 'custom-mock-conf.js');
            fs.watch(customMock, () => {
                childProcess.exec('node ' + mockGenerate, (err, std) => {
                    console.log(std);
                });
            });
        } catch (error) {
            console.log('watch custom mock error', '\n', error);
        }
    return {
        plugins,
        // ... other configs
    }
})

然后开启 mock 开发 即可: yarn start-with-mock