vite-plugin-mock-data 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +155 -0
  2. package/index.d.ts +22 -0
  3. package/index.js +134 -0
  4. package/package.json +29 -0
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # vite-plugin-mock-data
2
+
3
+ [![npm package](https://nodei.co/npm/vite-plugin-mock-data.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/vite-plugin-mock-data)
4
+
5
+ > Provides a simple way to mock data.
6
+
7
+ [![NPM version](https://img.shields.io/npm/v/vite-plugin-mock-data.svg?style=flat)](https://npmjs.org/package/vite-plugin-mock-data)
8
+ [![NPM Downloads](https://img.shields.io/npm/dm/vite-plugin-mock-data.svg?style=flat)](https://npmjs.org/package/vite-plugin-mock-data)
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install vite-plugin-mock-data --save-dev
14
+ ```
15
+
16
+ ## Options
17
+
18
+ * `isAfter` - If `true`, these mock routes is matched before internal middlewares are installed.
19
+ * `mockAssetsDir` - Specify the directory to define mock assets.
20
+ * `mockRouterOptions` - [Initial options of `find-my-way`'](https://github.com/delvedor/find-my-way#findmywayoptions)
21
+ * `mockRoutes` - Initial list of mock routes that should be added to the dev server.
22
+ * `mockRoutesDir` - Specify the directory to define mock routes that should be added to the dev server.
23
+
24
+ ## Usage
25
+
26
+ ### Specify the directory to define mock assets
27
+
28
+ ```js
29
+ import mockData from 'vite-plugin-mock-data';
30
+
31
+ export default defineConfig({
32
+ plugins: [
33
+ mockData({
34
+ mockAssetsDir: './mockAssets'
35
+ })
36
+ ]
37
+ });
38
+ ```
39
+
40
+ ```txt
41
+ .
42
+ ├── mockAssets
43
+ │ ├── test.zip
44
+ │ └── test.json
45
+ ```
46
+
47
+ ```js
48
+ fetch('/test.json')
49
+ .then(res => res.json())
50
+ .then((json) => {
51
+ console.log(json);
52
+ });
53
+ ```
54
+
55
+ ```html
56
+ <a class="download" href="./test.zip">Download</a>
57
+ ```
58
+
59
+ ### add mock routes to the dev server
60
+
61
+ ```js
62
+ import mockData from 'vite-plugin-mock-data';
63
+
64
+ export default defineConfig({
65
+ plugins: [
66
+ mockData({
67
+ mockRoutes: {
68
+ '/hello': 'hello',
69
+ '/hello2'(req, res) {
70
+ res.statusCode = 200;
71
+ res.setHeader('Content-Type', 'text/html');
72
+ res.end('hello2');
73
+ },
74
+ '/hello3': {
75
+ handler(req, res) {
76
+ res.statusCode = 200;
77
+ res.setHeader('Content-Type', 'text/html');
78
+ res.end('hello3');
79
+ }
80
+ },
81
+ '/json': {
82
+ handler: { hello: 1 }
83
+ }
84
+ '/package.json': {
85
+ file: './package.json'
86
+ },
87
+ }
88
+ })
89
+ ]
90
+ });
91
+ ```
92
+
93
+ ```js
94
+ fetch('/package.json')
95
+ .then(res => res.json())
96
+ .then((json) => {
97
+ console.log(json);
98
+ });
99
+ ```
100
+
101
+ ### Specify the directory to add mock routes to the dev server
102
+
103
+ ```js
104
+ import mockData from 'vite-plugin-mock-data';
105
+
106
+ export default defineConfig({
107
+ plugins: [
108
+ mockData({
109
+ mockRoutesDir: './mock'
110
+ })
111
+ ]
112
+ });
113
+ ```
114
+
115
+ ```txt
116
+ .
117
+ ├── mock
118
+ │ └── test.js
119
+ ```
120
+
121
+ ```js
122
+ module.exports = {
123
+ '/hello': 'hello',
124
+ '/hello2'(req, res) {
125
+ res.statusCode = 200;
126
+ res.setHeader('Content-Type', 'text/html');
127
+ res.end('hello2');
128
+ },
129
+ '/hello3': {
130
+ handler(req, res) {
131
+ res.statusCode = 200;
132
+ res.setHeader('Content-Type', 'text/html');
133
+ res.end('hello3');
134
+ }
135
+ },
136
+ '/json': {
137
+ handler: { hello: 1 }
138
+ }
139
+ '/package.json': {
140
+ file: './package.json'
141
+ },
142
+ };
143
+ ```
144
+
145
+ ```js
146
+ fetch('/package.json')
147
+ .then(res => res.json())
148
+ .then((json) => {
149
+ console.log(json);
150
+ });
151
+ ```
152
+
153
+ ## Examples
154
+
155
+ **[See demo](examples/demo-mock-data)**
package/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { Plugin } from 'vite';
2
+ import { IncomingMessage, ServerResponse } from 'http';
3
+ import Router from 'find-my-way';
4
+
5
+ export function Handler (req: IncomingMessage, res: ServerResponse): void;
6
+
7
+ export interface HandleRoute {
8
+ file?: string;
9
+ handler?: string | Handler;
10
+ }
11
+
12
+ export type RouteConfig = string | HandleRoute;
13
+
14
+ export interface Options {
15
+ isAfter?: boolean;
16
+ mockAssetsDir: string;
17
+ mockRouterOptions?: Router.Config;
18
+ mockRoutes?: RouteConfig | RouteConfig[]
19
+ mockRoutesDir?: string;
20
+ }
21
+
22
+ export default function createPlugin(options?: Options): Plugin;
package/index.js ADDED
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+
3
+ const globby = require('globby');
4
+ const { isAbsolute, join, parse } = require('path');
5
+ const Router = require('find-my-way');
6
+ const { send } = require('vite');
7
+ const sirv = require('sirv');
8
+
9
+ function isObject(val) {
10
+ return val && typeof val === 'object';
11
+ }
12
+
13
+ function sirvOptions(headers) {
14
+ return {
15
+ dev: true,
16
+ etag: true,
17
+ extensions: [],
18
+ setHeaders(res, pathname) {
19
+ res.setHeader('Access-Control-Allow-Origin', '*');
20
+ if (/\.[tj]sx?$/.test(pathname)) {
21
+ res.setHeader('Content-Type', 'application/javascript');
22
+ }
23
+ if (headers) {
24
+ // eslint-disable-next-line guard-for-in
25
+ for (const name in headers) {
26
+ res.setHeader(name, headers[name]);
27
+ }
28
+ }
29
+ }
30
+ };
31
+ }
32
+
33
+ function configureServer(server, routerOpts, routes, serve) {
34
+ const router = new Router(routerOpts);
35
+ if (Array.isArray(routes)) {
36
+ routes.forEach((route) => {
37
+ Object.keys(route).forEach((xpath) => {
38
+ let [methods, pathname] = xpath.split(' ');
39
+ if (!pathname) {
40
+ pathname = methods;
41
+ methods = 'GET';
42
+ }
43
+ let handler = route[xpath];
44
+ let file;
45
+ if (!isObject(handler)) {
46
+ handler = { handler };
47
+ }
48
+ else if ((file = handler.file)) {
49
+ handler.handler = (req, res) => {
50
+ file = isAbsolute(file) ? file : join(process.cwd(), file);
51
+ const parsedPath = parse(file);
52
+ const serve = sirv(parsedPath.dir, sirvOptions(server.config.server.headers));
53
+ req.url = `/${parsedPath.base}`;
54
+ serve(req, res);
55
+ };
56
+ }
57
+ if (typeof handler.handler !== 'function') {
58
+ const ret = handler.handler;
59
+ const retType = typeof ret;
60
+ handler.handler = (req, res) => {
61
+ send(
62
+ req,
63
+ res,
64
+ retType !== 'string' ? JSON.stringify(ret) : ret,
65
+ isObject(ret) ? 'json' : 'html',
66
+ {
67
+ headers: server.config.server.headers
68
+ }
69
+ );
70
+ };
71
+ }
72
+
73
+ router.on(
74
+ methods.split('/'),
75
+ pathname,
76
+ handler.opts || {},
77
+ handler.handler,
78
+ handler.store
79
+ );
80
+ });
81
+ });
82
+ }
83
+
84
+ if (serve) {
85
+ server.middlewares.use(serve);
86
+ }
87
+
88
+ server.middlewares.use((req, res, next) => {
89
+ router.defaultRoute = () => next();
90
+ router.lookup(req, res);
91
+ });
92
+ }
93
+
94
+ module.exports = function (opts = {}) {
95
+ const {
96
+ isAfter,
97
+ mockRouterOptions,
98
+ mockAssetsDir
99
+ } = opts;
100
+ let {
101
+ mockRoutesDir,
102
+ mockRoutes = []
103
+ } = opts;
104
+
105
+ if (isObject(mockRoutes) && !Array.isArray(mockRoutes)) {
106
+ mockRoutes = [mockRoutes];
107
+ }
108
+
109
+ return {
110
+ name: 'vite:mock-data',
111
+
112
+ configureServer(server) {
113
+ if (mockRoutesDir) {
114
+ mockRoutesDir = isAbsolute(mockRoutesDir) ? mockRoutesDir : join(process.cwd(), mockRoutesDir);
115
+ globby.sync(`${mockRoutesDir}/**/*.js`).forEach((file) => {
116
+ delete require.cache[file];
117
+ mockRoutes.push(require(file));
118
+ });
119
+ }
120
+
121
+ let serve;
122
+ if (mockAssetsDir) {
123
+ serve = sirv(
124
+ isAbsolute(mockAssetsDir) ? mockAssetsDir : join(process.cwd(), mockAssetsDir),
125
+ sirvOptions(server.config.server.headers)
126
+ );
127
+ }
128
+
129
+ return isAfter
130
+ ? () => configureServer(server, mockRouterOptions, mockRoutes, serve)
131
+ : configureServer(server, mockRouterOptions, mockRoutes, serve);
132
+ }
133
+ };
134
+ };
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "vite-plugin-mock-data",
3
+ "version": "1.0.0",
4
+ "description": "Provides a simple way to mock data.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "release": "npm publish"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/fengxinming/vite-plugins.git",
12
+ "directory": "packages/vite-plugin-mock-data"
13
+ },
14
+ "keywords": [
15
+ "vite-plugin",
16
+ "vite-plugin-mock-data"
17
+ ],
18
+ "author": "Jesse Feng <fxm0016@126.com>",
19
+ "license": "MIT",
20
+ "bugs": {
21
+ "url": "https://github.com/fengxinming/vite-plugins/issues"
22
+ },
23
+ "homepage": "https://github.com/fengxinming/vite-plugins#readme",
24
+ "dependencies": {
25
+ "find-my-way": "^7.0.0",
26
+ "globby": "^11.1.0",
27
+ "sirv": "^2.0.2"
28
+ }
29
+ }