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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zhennann/vite-plugin-fake-server

v2.1.2

Published

A fake server plugin for Vite.

Downloads

19

Readme

Vite-plugin-fake-server

NPM version Downloads License GitHub stars

A fake server plugin for Vite. Live Demo

Features

  • Simple to use, configuration file driven.
  • Support ECMAScript modules(ESM) and CommonJS modules(CommonJS).
  • Friendly type prompt - defineFakeRoute.
  • No reliance on fake library - you can use @faker-js/faker or mockjs and so on.
  • Support HTTP/1 and HTTP/2 - http2 option.
  • Support ts, js, mjs, cjs, cts, mts files.
  • Support multiple response methods - responseType.
  • Support custom response headers.
  • Support development and production environments.
  • Support exporting independent deployment services - build option.
  • Support interception XHR and Fetch request - XHook.
  • Support requesting real URL.

Install

npm install --save-dev vite-plugin-fake-server

Usage

Configure plugins in the configuration file of Vite, such as vite.config.ts:

// vite.config.ts
import { defineConfig } from "vite";
import { vitePluginFakeServer } from "vite-plugin-fake-server";

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [
		vitePluginFakeServer(),
	],
});

You can create a new file in the fake folder in the directory where the Vite configuration file is located, such as user.fake.ts:

// fake/user.fake.ts
import Mock from "mockjs";
import { defineFakeRoute } from "vite-plugin-fake-server/client";
import { faker } from "@faker-js/faker";

export default defineFakeRoute([
	{
		url: "/mock/get-user-info",
		response: () => {
			return Mock.mock({
				id: "@guid",
				username: "@first",
				email: "@email",
				avatar: '@image("200x200")',
				role: "admin",
			});
		},
	},
	{
		url: "/fake/get-user-info",
		response: () => {
			return {
				id: faker.string.uuid(),
				avatar: faker.image.avatar(),
				birthday: faker.date.birthdate(),
				email: faker.internet.email(),
				firstName: faker.person.firstName(),
				lastName: faker.person.lastName(),
				sex: faker.person.sexType(),
				role: "admin",
			};
		},
	},
]);

After starting the project through Vite, you can request the custom URL above through XHR or Fetch.

For case details, please click this link to view some examples or experience it directly online - Live Demo

defineFakeRoute

The defineFakeRoute function parameters require the user to enter the route type as follows:

export interface FakeRoute {
	url: string;
	method?: HttpMethodType;
	timeout?: number;
	statusCode?: number;
	statusText?: string;
	headers?: OutgoingHttpHeaders;
	response?: (processedRequest: ProcessedRequest, req: IncomingMessage, res: ServerResponse) => any;
	rawResponse?: (req: IncomingMessage, res: ServerResponse) => void;
}

export function defineFakeRoute(config: FakeRoute | FakeRoute[]) {
	return config;
}

API

vitePluginFakeServer(options?)

options

include

Type: string
Default: "fake"

Set the folder where the fake xxx.fake.{ts,js,mjs,cjs,cts,mts} files is stored.

exclude

Type: string[]
Default: []

Exclude files in the include directory.

document: https://github.com/mrmlnc/fast-glob#ignore

infixName

Type: string | boolean
Default: "fake"

Set the infix name used in the fake file name.

watch

Type: boolean
Default: true

Set whether to listen to include files.

logger

Type: boolean
Default: true

Set whether to display the request log on the console.

In order to maintain logs and screen clearing strategies consistent with Vite style on the terminal, the vite-plugin-fake-server plugin will automatically read the following three parameters in the Vite configuration file or in the Vite command line.

A preview image:

shapes at 23-10-24 15 23 18

extensions

Type: string[]
Default: ["ts", "js", "mjs", "cjs", "cts", "mts"]

Set the fake files extensions.

timeout

Type: number
Default: undefined

Set default response delay time.

basename

Type: string
Default: ""

Set the root address of the request URL.

headers

Type: OutgoingHttpHeaders
Default: {}

Set default headers for responses.

enableDev

Type: boolean
Default: true

Set up the service simulator in the development environment.

Powered by Connect technology.

enableProd

Type: boolean
Default: false

Set up the service simulator in the production environment.

Powered by XHook technology.

⚠️ The node module cannot be used in the fake file, otherwise the production environment will fail.As an alternative to keep consistent with the development environment, you can build a standalone deployment server, see build option.

Compared with the development environment, the API interface defined in the production environment does not have a rawResponse function. The response function does not have the second parameter request and the third parameter response.

export interface FakeRoute {
	url: string;
	method?: HttpMethodType;
	timeout?: number;
	statusCode?: number;
	statusText?: string;
	headers?: OutgoingHttpHeaders;
	response?: (processedRequest: ProcessedRequest) => any;
}
http2

Type: boolean

Clarify that the plugin runs on the HTTP/2 protocol. By default, automatically follow Vite's server-https configuration.

The status text in HTTP/2 is always an empty string.

build

Type: boolean | ServerBuildOptions
Default: false

Set whether to export a independently deployable fake service(only valid in build mode).

interface ServerBuildOptions {
	/**
	 * @description Server port
	 * @default 8888
	 */
	port?: number;
	/**
	 * Directory relative from `root` where build output will be placed. If the
	 * directory exists, it will be removed before the build.
	 * @default "fakeServer"
	 */
	outDir?: string;
}

Principle

vite-plugin-fake-server

Appreciation

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature

Debugging

In development environment

# packages/vite-plugin-fake-server
npm run build:watch


# packages/playground/react-sample
npm run dev

In production environment

# packages/vite-plugin-fake-server
npm run build:watch


# packages/playground/react-sample
npm run build
npm run preview
  1. Commit your changes: git commit -am "Add some feature"
  2. Push to the branch: git push origin my-new-feature
  3. Submit a pull request :D

License

MIT License © 2023-Present Condor Hero