Repository: anncwb/vite-plugin-mock Branch: main Commit: ca2e9eabf170 Files: 56 Total size: 99.7 KB Directory structure: gitextract_g6l1iabh/ ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ ├── publish.yml │ └── release.yml ├── .gitignore ├── .husky/ │ ├── .gitignore │ ├── commit-msg │ ├── common.sh │ ├── lintstagedrc.js │ └── pre-commit ├── .prettierignore ├── .vscode/ │ ├── extensions.json │ └── settings.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── README.zh_CN.md ├── commitlint.config.js ├── package.json ├── packages/ │ ├── playground/ │ │ ├── js-example/ │ │ │ ├── .gitignore │ │ │ ├── index.html │ │ │ ├── mock/ │ │ │ │ ├── role.mjs │ │ │ │ └── user.js │ │ │ ├── package.json │ │ │ ├── src/ │ │ │ │ ├── App.vue │ │ │ │ ├── main.js │ │ │ │ └── mockProdServer.js │ │ │ └── vite.config.js │ │ └── ts-example/ │ │ ├── .gitignore │ │ ├── index.html │ │ ├── mock/ │ │ │ ├── define.ts │ │ │ ├── dep/ │ │ │ │ └── role.ts │ │ │ └── user.ts │ │ ├── package.json │ │ ├── shim-vue.ts │ │ ├── src/ │ │ │ ├── App.vue │ │ │ ├── main.ts │ │ │ └── mockProdServer.ts │ │ ├── tsconfig.json │ │ └── vite.config.ts │ └── vite-plugin-mock/ │ ├── CHANGELOG.md │ ├── build.config.ts │ ├── package.json │ ├── src/ │ │ ├── client.ts │ │ ├── createMockServer.ts │ │ ├── index.ts │ │ ├── types.ts │ │ └── utils.ts │ └── tsconfig.json ├── pnpm-workspace.yaml ├── prettier.config.js ├── tests/ │ └── index.spec.ts ├── tsconfig.es.json └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 end_of_line = lf trim_trailing_whitespace = true insert_final_newline = true [*.md] insert_final_newline = false trim_trailing_whitespace = false [*.{js,jsx,json,ts,tsx,yml}] indent_size = 2 indent_style = space ================================================ FILE: .eslintignore ================================================ dist node_modules example ================================================ FILE: .eslintrc.js ================================================ module.exports = { root: true, env: { browser: true, es2021: true, es6: true, node: true, }, extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier', ], parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 12, sourceType: 'module', }, plugins: ['@typescript-eslint'], rules: { 'no-console': 'off', '@typescript-eslint/no-var-requires': 'off', '@typescript-eslint/no-non-null-assertion': 'off', '@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-unused-vars': 'off', }, } ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: 'yarn' directory: '/' schedule: interval: 'daily' ================================================ FILE: .github/workflows/publish.yml ================================================ name: Npm Publish on: push: branches: - main jobs: publish-npm: if: "contains(github.event.head_commit.message, 'release')" runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 - name: use Node.js 20 uses: actions/setup-node@v1 with: registry-url: https://registry.npmjs.org/ node-version: 20 - name: pnpm install and publish run: | npm i -g pnpm pnpm install pnpm publish --filter=./packages/vite-plugin-mock env: NODE_AUTH_TOKEN: ${{secrets.npm_token}} ================================================ FILE: .github/workflows/release.yml ================================================ name: Create Release on: push: tags: - v* jobs: build: name: Create Release runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@master - name: Create Release for Tag id: release_tag uses: yyx990803/release-tag@master env: GITHUB_TOKEN: ${{ secrets.OPER_TOKEN }} with: tag_name: ${{ github.ref }} body: | Please refer to [CHANGELOG.md](https://github.com/anncwb/vite-plugin-mock/blob/main/CHANGELOG.md) for details. # - name: npm install and create changeLog # run: | # npm install # npm run log ================================================ FILE: .gitignore ================================================ node_modules .DS_Store dist es .npmrc .cache test/upload-server/static .local # local env files .env.local .env.*.local # Log files npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* # Editor directories and files .idea # .vscode *.suo *.ntvs* *.njsproj *.sln *.sw? coverage ================================================ FILE: .husky/.gitignore ================================================ _ ================================================ FILE: .husky/commit-msg ================================================ #!/bin/sh # shellcheck source=./_/husky.sh . "$(dirname "$0")/_/husky.sh" npx --no-install commitlint --edit "$1" ================================================ FILE: .husky/common.sh ================================================ #!/bin/sh command_exists () { command -v "$1" >/dev/null 2>&1 } # Workaround for Windows 10, Git Bash and Yarn if command_exists winpty && test -t 1; then exec < /dev/tty fi ================================================ FILE: .husky/lintstagedrc.js ================================================ module.exports = { '*.{js,jsx,ts,tsx}': ['eslint --fix', 'prettier --write'], '{!(package)*.json,*.code-snippets,.!(browserslist)*rc}': ['prettier --write--parser json'], 'package.json': ['prettier --write'], '*.md': ['prettier --write'], } ================================================ FILE: .husky/pre-commit ================================================ #!/bin/sh . "$(dirname "$0")/_/husky.sh" . "$(dirname "$0")/common.sh" [ -n "$CI" ] && exit 0 # Format and submit code according to lintstagedrc.js configuration npm run lint:lint-staged ================================================ FILE: .prettierignore ================================================ dist/ node_modules ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "octref.vetur", "dbaeumer.vscode-eslint", "stylelint.vscode-stylelint", "esbenp.prettier-vscode", "mrmlnc.vscode-less", "lokalise.i18n-ally", "antfu.iconify", "mikestead.dotenv", "heybourn.headwind" ] } ================================================ FILE: .vscode/settings.json ================================================ { "typescript.tsdk": "./node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true, //=========================================== //============= Editor ====================== //=========================================== "explorer.openEditors.visible": 0, "editor.tabSize": 2, "editor.defaultFormatter": "esbenp.prettier-vscode", "diffEditor.ignoreTrimWhitespace": false, //=========================================== //============= Other ======================= //=========================================== "breadcrumbs.enabled": true, "open-in-browser.default": "chrome", //=========================================== //============= files ======================= //=========================================== "files.eol": "\n", "search.exclude": { "**/node_modules": true, "**/*.log": true, "**/*.log*": true, "**/bower_components": true, "**/dist": true, "**/elehukouben": true, "**/.git": true, "**/.gitignore": true, "**/.svn": true, "**/.DS_Store": true, "**/.idea": true, "**/.vscode": false, "**/yarn.lock": true, "**/tmp": true, "out": true, "dist": true, "node_modules": true, "CHANGELOG.md": true, "examples": true, "res": true, "screenshots": true, "yarn-error.log": true, "**/.yarn": true }, "files.exclude": { "**/.cache": true, "**/.editorconfig": true, "**/.eslintcache": true, "**/bower_components": true, "**/.idea": true, "**/tmp": true, "**/.git": true, "**/.svn": true, "**/.hg": true, "**/CVS": true, "**/.DS_Store": true }, "files.watcherExclude": { "**/.git/objects/**": true, "**/.git/subtree-cache/**": true, "**/.vscode/**": true, "**/node_modules/**": true, "**/tmp/**": true, "**/bower_components/**": true, "**/dist/**": true, "**/yarn.lock": true }, "stylelint.enable": true, "stylelint.packageManager": "yarn", "liveServer.settings.donotShowInfoMsg": true, "telemetry.enableCrashReporter": false, "workbench.settings.enableNaturalLanguageSearch": false, "path-intellisense.mappings": { "/@/": "${workspaceRoot}/src" }, "prettier.requireConfig": true, "typescript.updateImportsOnFileMove.enabled": "always", "workbench.sideBar.location": "left", "[javascriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[html]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[css]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[less]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[scss]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[markdown]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "[vue]": { "editor.codeActionsOnSave": { "source.fixAll.eslint": false } }, "i18n-ally.localesPaths": ["src/locales/lang"], "i18n-ally.keystyle": "nested", "i18n-ally.sortKeys": true, "i18n-ally.namespace": true, "i18n-ally.pathMatcher": "{locale}/{namespaces}.{ext}", "i18n-ally.enabledParsers": ["ts"], "i18n-ally.sourceLanguage": "en", "i18n-ally.displayLanguage": "zh-CN", "i18n-ally.enabledFrameworks": ["vue", "react"], "cSpell.words": [ "vben", "windi", "browserslist", "tailwindcss", "esnext", "antv", "tinymce", "qrcode", "sider", "pinia", "sider", "nprogress", "INTLIFY", "stylelint", "esno", "vitejs", "sortablejs", "mockjs", "codemirror", "iconify", "commitlint", "vditor", "echarts", "cropperjs", "logicflow", "vueuse", "zxcvbn", "lintstagedrc", "brotli", "tailwindcss", "sider" ] } ================================================ FILE: CHANGELOG.md ================================================ ## [3.0.0] ### Breaking Change - Remove the `localEnabled` and `prodEnabled` configuration and use the `enable` configuration instead, no longer distinguishing the environment - Remove the `injectFile`、`injectCode` and `supportTs` configuration - Minimum requirement NodeJs 16 - Production Environment Syntax Changes ```ts // vite-plugin-mock/es/createProdMockServer => vite-plugin-mock/client import { createProdMockServer } from 'vite-plugin-mock/client' import roleMock from '../mock/dep/role' // functional form import userMockFn from '../mock/user' export async function setupProdMockServer() { const mockModules = [...roleMock, ...userMockFn()] createProdMockServer(mockModules) } ``` ### Features - Upgrade all dependencies to latest - support `vite4` and `rollup3` - The function module supports returning a function ```ts import type { MockConfig } from 'vite-plugin-mock' export default (config?: MockConfig) => { return [ { url: '/api/createUser', method: 'post', response: ({ body, query }) => { console.log('body>>>>>>>>', body) console.log('query>>>>>>>>', query) return { code: 0, message: 'ok', data: { a: 21, 'import.meta.url': import.meta.url }, } }, }, ] } ``` ## [2.9.8](https://github.com/vbenjs/vite-plugin-mock/compare/v2.9.0...v2.9.8) (2023-04-17) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/vbenjs/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/vbenjs/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - error handle, fix [#39](https://github.com/vbenjs/vite-plugin-mock/issues/39) ([874318c](https://github.com/vbenjs/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/vbenjs/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/vbenjs/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/vbenjs/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) - inappropriate type annotation ([#90](https://github.com/vbenjs/vite-plugin-mock/issues/90)) ([a3fc4aa](https://github.com/vbenjs/vite-plugin-mock/commit/a3fc4aab3dd1864f640918516c10d7d1530f5d90)) - typo, close [#42](https://github.com/vbenjs/vite-plugin-mock/issues/42) ([5b4e946](https://github.com/vbenjs/vite-plugin-mock/commit/5b4e9469060109a2a28c079eec8384fe654be68e)) ### Features - **prod:** response 在 prod 模式下入参对象加上 url ([#83](https://github.com/vbenjs/vite-plugin-mock/issues/83)) ([cd0b86f](https://github.com/vbenjs/vite-plugin-mock/commit/cd0b86fce20228094cf18be14194498a2cbd490e)) - **server:** add this for response, rawResponse function ([#43](https://github.com/vbenjs/vite-plugin-mock/issues/43)) ([2f4d6d2](https://github.com/vbenjs/vite-plugin-mock/commit/2f4d6d2984c7fe15236cb8b0d2ec5479930d5668)) ## [2.9.8](https://github.com/anncwb/vite-plugin-mock/compare/v2.9.0...v2.9.8) (2023-04-16) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/anncwb/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/anncwb/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - error handle, fix [#39](https://github.com/anncwb/vite-plugin-mock/issues/39) ([874318c](https://github.com/anncwb/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/anncwb/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/anncwb/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) - inappropriate type annotation ([#90](https://github.com/anncwb/vite-plugin-mock/issues/90)) ([a3fc4aa](https://github.com/anncwb/vite-plugin-mock/commit/a3fc4aab3dd1864f640918516c10d7d1530f5d90)) - typo, close [#42](https://github.com/anncwb/vite-plugin-mock/issues/42) ([5b4e946](https://github.com/anncwb/vite-plugin-mock/commit/5b4e9469060109a2a28c079eec8384fe654be68e)) ### Features - **prod:** response 在 prod 模式下入参对象加上 url ([#83](https://github.com/anncwb/vite-plugin-mock/issues/83)) ([cd0b86f](https://github.com/anncwb/vite-plugin-mock/commit/cd0b86fce20228094cf18be14194498a2cbd490e)) - **server:** add this for response, rawResponse function ([#43](https://github.com/anncwb/vite-plugin-mock/issues/43)) ([2f4d6d2](https://github.com/anncwb/vite-plugin-mock/commit/2f4d6d2984c7fe15236cb8b0d2ec5479930d5668)) ## [2.9.6](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.6) (2021-08-23) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/anncwb/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/anncwb/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - error handle, fix [#39](https://github.com/anncwb/vite-plugin-mock/issues/39) ([874318c](https://github.com/anncwb/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/anncwb/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/anncwb/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) - typo, close [#42](https://github.com/anncwb/vite-plugin-mock/issues/42) ([5b4e946](https://github.com/anncwb/vite-plugin-mock/commit/5b4e9469060109a2a28c079eec8384fe654be68e)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) - **server:** add this for response, rawResponse function ([#43](https://github.com/anncwb/vite-plugin-mock/issues/43)) ([2f4d6d2](https://github.com/anncwb/vite-plugin-mock/commit/2f4d6d2984c7fe15236cb8b0d2ec5479930d5668)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.9.5](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.5) (2021-08-23) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/anncwb/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/anncwb/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - error handle, fix [#39](https://github.com/anncwb/vite-plugin-mock/issues/39) ([874318c](https://github.com/anncwb/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/anncwb/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/anncwb/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) - **server:** add this for response, rawResponse function ([#43](https://github.com/anncwb/vite-plugin-mock/issues/43)) ([2f4d6d2](https://github.com/anncwb/vite-plugin-mock/commit/2f4d6d2984c7fe15236cb8b0d2ec5479930d5668)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.9.4](https://github.com/anncwb/vite-plugin-mock/compare/v2.9.0...v2.9.4) (2021-08-01) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/anncwb/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/anncwb/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - error handle, fix [#39](https://github.com/anncwb/vite-plugin-mock/issues/39) ([874318c](https://github.com/anncwb/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/anncwb/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/anncwb/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) ## [2.9.3](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.3) (2021-07-18) ### Bug Fixes - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.9.2](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.2) (2021-07-18) ### Bug Fixes - ensure file changes take effect,fix [#36](https://github.com/anncwb/vite-plugin-mock/issues/36) ([353aa9d](https://github.com/anncwb/vite-plugin-mock/commit/353aa9db67483072a3d60b6bf3c99736563bba43)) - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.9.1](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.1) (2021-07-06) ### Bug Fixes - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - fix js parsing error ([d2746b6](https://github.com/anncwb/vite-plugin-mock/commit/d2746b6d788cdd304cac8512afa743b01edbd479)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) # [2.9.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.0) (2021-07-05) ### Bug Fixes - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) # [2.8.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.8.0) (2021-06-16) ### Bug Fixes - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([bfed256](https://github.com/anncwb/vite-plugin-mock/commit/bfed256bff42e2348b30a6b31746854b18fc90b8)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([a341c7d](https://github.com/anncwb/vite-plugin-mock/commit/a341c7d5b2de153593c0d1f5dab00b1b730a6819)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.7.2](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.7.2) (2021-06-10) ### Bug Fixes - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.7.1](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.7.1) (2021-06-09) ### Bug Fixes - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) # [2.6.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.6.0) (2021-05-29) ### Bug Fixes - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) # [2.5.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.4.0...v2.5.0) (2021-04-06) ### Bug Fixes - production xhr ([6c94783](https://github.com/anncwb/vite-plugin-mock/commit/6c94783f07b27c6ac58a4642c0e7eddf34b06f1f)) - **eslint warn:** fix some warn ([b44c13b](https://github.com/anncwb/vite-plugin-mock/commit/b44c13b766cda0ee310071e9febeb48d73ef7bde)) - empty TS file in mock folder is error ([669b804](https://github.com/anncwb/vite-plugin-mock/commit/669b804df31f537bf6985b56972b32dd11e20504)) ### Features - add rawResponse option to MockMethod ([#17](https://github.com/anncwb/vite-plugin-mock/issues/17)) ([24775f9](https://github.com/anncwb/vite-plugin-mock/commit/24775f9d7b14d024d90cd36c850a00634341927f)), closes [#16](https://github.com/anncwb/vite-plugin-mock/issues/16) ### Performance Improvements - perf code ([98b9dbc](https://github.com/anncwb/vite-plugin-mock/commit/98b9dbc64f5c6da815a1f29c6b588fddd5189370)) ## [2.4.1](https://github.com/anncwb/vite-plugin-mock/compare/v2.4.0...v2.4.1) (2021-03-30) ### Bug Fixes - empty TS file in mock folder is error ([669b804](https://github.com/anncwb/vite-plugin-mock/commit/669b804df31f537bf6985b56972b32dd11e20504)) ### Performance Improvements - perf code ([98b9dbc](https://github.com/anncwb/vite-plugin-mock/commit/98b9dbc64f5c6da815a1f29c6b588fddd5189370)) # [2.4.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.3.0...v2.4.0) (2021-03-25) ### Features - response return headers, close [#10](https://github.com/anncwb/vite-plugin-mock/issues/10) ([bcb7abd](https://github.com/anncwb/vite-plugin-mock/commit/bcb7abd98e8726af6f1721ad021c06028b1ffca7)) ## [2.2.4](https://github.com/anncwb/vite-plugin-mock/compare/v2.2.3...v2.2.4) (2021-03-10) ### Features - support post restful close [#7](https://github.com/anncwb/vite-plugin-mock/issues/7) ([70b51e8](https://github.com/anncwb/vite-plugin-mock/commit/70b51e8738e41a7011e38e942dd2a136e450ae9f)) ## [2.2.3](https://github.com/anncwb/vite-plugin-mock/compare/v2.2.0...v2.2.3) (2021-03-10) ### Bug Fixes - ensure that the URLs of different request methods cannot match close [#6](https://github.com/anncwb/vite-plugin-mock/issues/6) ([361a3eb](https://github.com/anncwb/vite-plugin-mock/commit/361a3eb62874f7a6dce8cdc8add4487302c3ee04)) ### Features - support restful api close [#4](https://github.com/anncwb/vite-plugin-mock/issues/4) ([236393e](https://github.com/anncwb/vite-plugin-mock/commit/236393ef551de32fbba62fbb27f678d4782568ec)) ## [2.2.1](https://github.com/anncwb/vite-plugin-mock/compare/v2.2.0...v2.2.1) (2021-03-09) ### Features - support restful api close [#4](https://github.com/anncwb/vite-plugin-mock/issues/4) ([7a35b1a](https://github.com/anncwb/vite-plugin-mock/commit/7a35b1a3af3bfa8623f1d24f53e71928df20b69b)) # [2.2.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.1.5...v2.2.0) (2021-03-02) ### Features - add logger option ([66a75ab](https://github.com/anncwb/vite-plugin-mock/commit/66a75ab0ee5a7c8e03987e74f15b50aedd1cc29f)) ## [2.1.5](https://github.com/anncwb/vite-plugin-mock/compare/v2.0.0-beta.1...v2.1.5) (2021-02-23) ### Bug Fixes - correct sourcemap ([2140987](https://github.com/anncwb/vite-plugin-mock/commit/21409876876b845b18b5b006e98292138870a922)) - dev sourcemap ([5834b4f](https://github.com/anncwb/vite-plugin-mock/commit/5834b4f621b25371a7b0246a48fb83b9761afeed)) - fix post proxy error ([d3ae41e](https://github.com/anncwb/vite-plugin-mock/commit/d3ae41e18a5e7adae504457165ba7b34b8ebff6f)) ### Features - support sourcemap ([8c3cd9d](https://github.com/anncwb/vite-plugin-mock/commit/8c3cd9d78a9bd7f87dc7900e9bfe6c753ff3b11f)) ### Performance Improvements - imporve request log ([f9353fd](https://github.com/anncwb/vite-plugin-mock/commit/f9353fdf8149665f984729ab3c7a6749022cfdaf)) # [2.0.0-beta.1](https://github.com/anncwb/vite-plugin-mock/compare/2.0.0-beta.1...v2.0.0-beta.1) (2021-01-03) ### Bug Fixes - Fix local development post request proxy to https ([7965604](https://github.com/anncwb/vite-plugin-mock/commit/79656046377f501da796d1be9752522a2203d69b)) - remove unnecessary and wrong usage of "try catch" ([815abde](https://github.com/anncwb/vite-plugin-mock/commit/815abde26f8f9a19322916ae01a9896a9aced33a)) ### Features - add request time ([ccbb14a](https://github.com/anncwb/vite-plugin-mock/commit/ccbb14ad623e6549781e5e902819f830a291f13f)) ## [1.0.2](https://github.com/anncwb/vite-plugin-mock/compare/1.0.1...1.0.2) (2020-09-14) ### Features - add examples ([2c5a86b](https://github.com/anncwb/vite-plugin-mock/commit/2c5a86bb75e39b6c7c9e08b1691c0541aeb104d9)) ## [1.0.1](https://github.com/anncwb/vite-plugin-mock/compare/58ad7cd57e3fd0daa92e0fc59c00e09cf6ba45ad...1.0.1) (2020-09-14) ### Features - add supportTs options,Support es6 and commonjs modules in .js folder ([37f83f5](https://github.com/anncwb/vite-plugin-mock/commit/37f83f54c3a34e049f967b0db0ac2ade401cbf58)) ### Performance Improvements - Replace typescript plug-in with a faster esbuild plug-in ([58ad7cd](https://github.com/anncwb/vite-plugin-mock/commit/58ad7cd57e3fd0daa92e0fc59c00e09cf6ba45ad)) ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2020-present, Vben Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # vite-plugin-mock **English** | [中文](./README.zh_CN.md) [![npm][npm-img]][npm-url] [![node][node-img]][node-url] Provide local and prod mocks for vite. A mock plugin for vite, developed based on mockjs. And support the local environment and production environment at the same time. Connect service middleware is used locally, mockjs is used online ### Install (yarn or npm) **node version:** >=12.0.0 **vite version:** >=2.0.0 ```bash yarn add mockjs # or npm i mockjs -S # or pnpm add mockjs ``` and ```bash yarn add vite-plugin-mock -D # or npm i vite-plugin-mock -D # or pnpm add vite-plugin-mock -D ``` ### Example **Run Example** ```bash # ts example cd ./examples/ts-examples yarn install yarn serve # js example cd ./examples/js-examples yarn install yarn serve ``` ## Usage **Development environment** The development environment is implemented using Connect middleware。 Different from the production environment, you can view the network request record in the Google Chrome console - Config plugin in vite.config.ts ```ts import { UserConfigExport, ConfigEnv } from 'vite' import { viteMockServe } from 'vite-plugin-mock' import vue from '@vitejs/plugin-vue' export default ({ command }: ConfigEnv): UserConfigExport => { return { plugins: [ vue(), viteMockServe({ // default mockPath: 'mock', enable: true, }), ], } } ``` - viteMockServe Options ```ts { mockPath?: string; ignore?: RegExp | ((fileName: string) => boolean); watchFiles?: boolean; enable?: boolean; ignoreFiles?: string[]; configPath?: string; } ``` ## Options ### mockPath **type:** `string` **default:** `'mock'` Set the folder where the mock .ts file is stored If `watchFiles:true`, the file changes in the folder will be monitored. And synchronize to the request result in real time If configPath has a value, it is invalid ### ignore **type:** `RegExp | ((fileName: string) => boolean);` **default:** `undefined` When automatically reading analog .ts files, ignore files in the specified format ### watchFiles **type:** `boolean` **default:** `true` Set whether to monitor changes in mock .ts files ### enable **type:** `boolean` **default:** true Whether to enable the mock function ### configPath **type:** `string` **default:** `vite.mock.config.ts` Set the data entry that the mock reads. When the file exists and is located in the project root directory, the file will be read and used first. The configuration file returns an array ### logger **type:** `boolean` **default:** `true` Whether to display the request log on the console ## Mock file example `/path/mock` ```ts // test.ts import { MockMethod, MockConfig } from 'vite-plugin-mock' export default [ { url: '/api/get', method: 'get', response: ({ query }) => { return { code: 0, data: { name: 'vben', }, } }, }, { url: '/api/post', method: 'post', timeout: 2000, response: { code: 0, data: { name: 'vben', }, }, }, { url: '/api/text', method: 'post', rawResponse: async (req, res) => { let reqbody = '' await new Promise((resolve) => { req.on('data', (chunk) => { reqbody += chunk }) req.on('end', () => resolve(undefined)) }) res.setHeader('Content-Type', 'text/plain') res.statusCode = 200 res.end(`hello, ${reqbody}`) }, }, ] as MockMethod[] export default function (config: MockConfig) { return [ { url: '/api/text', method: 'post', rawResponse: async (req, res) => { let reqbody = '' await new Promise((resolve) => { req.on('data', (chunk) => { reqbody += chunk }) req.on('end', () => resolve(undefined)) }) res.setHeader('Content-Type', 'text/plain') res.statusCode = 200 res.end(`hello, ${reqbody}`) }, }, ] } ``` ### MockMethod ```ts { // request url url: string; // request method method?: MethodType; // Request time in milliseconds timeout?: number; // default: 200 statusCode?:number; // response data (JSON) response?: ((opt: { [key: string]: string; body: Record; query: Record, headers: Record; }) => any) | any; // response (non-JSON) rawResponse?: (req: IncomingMessage, res: ServerResponse) => void; } ``` ### Example (3.0.0 recommended) Create the `mockProdServer.ts` file ```ts // mockProdServer.ts import { createProdMockServer } from 'vite-plugin-mock/client' // Import your mock .ts files one by one // If you use vite.mock.config.ts, just import the file directly // You can use the import.meta.glob function to import all import testModule from '../mock/test' export function setupProdMockServer() { createProdMockServer([...testModule]) } ``` Config `vite-plugin-mock` ```ts import { viteMockServe } from 'vite-plugin-mock' import { UserConfigExport, ConfigEnv } from 'vite' export default ({ command }: ConfigEnv): UserConfigExport => { return { plugins: [ viteMockServe({ mockPath: 'mock', // According to the project configuration. Can be configured in the .env file enable: true, }), ], } } ``` ## Sample project [Vben Admin](https://github.com/anncwb/vue-vben-admin) ## Note - The node module cannot be used in the mock .ts file, otherwise the production environment will fail - Mock is used in the production environment, which is only suitable for some test environments. Do not open it in the formal environment to avoid unnecessary errors. At the same time, in the production environment, it may affect normal Ajax requests, such as file upload failure, etc. ## License MIT [npm-img]: https://img.shields.io/npm/v/vite-plugin-mock.svg [npm-url]: https://npmjs.com/package/vite-plugin-mock [node-img]: https://img.shields.io/node/v/vite-plugin-mock.svg [node-url]: https://nodejs.org/en/about/releases/ ================================================ FILE: README.zh_CN.md ================================================ # vite-plugin-mock **中文** | [English](./README.md) [![npm][npm-img]][npm-url] [![node][node-img]][node-url] 提供本地和生产模拟服务。 vite 的数据模拟插件,是基于 vite.js 开发的。 并同时支持本地环境和生产环境。 Connect 服务中间件在本地使用,mockjs 在生产环境中使用。 ## Production environment problem description The current production environment cannot support the acquisition of `headers` and the acquisition of `restful`Url format parameters. So there are those two formats that need to be used in the production environment. ### 安装 (yarn or npm) **node version:** >=12.0.0 **vite version:** >=2.0.0 ```bash yarn add mockjs # or npm i mockjs -S # or pnpm add mockjs ``` and ```bash yarn add vite-plugin-mock -D # or npm i vite-plugin-mock -D # or pnpm add vite-plugin-mock -D ``` ## 使用 **开发环境** 开发环境是使用 Connect 中间件实现的。 与生产环境不同,您可以在 Google Chrome 控制台中查看网络请求记录 - vite.config.ts 配置 ```ts import { UserConfigExport, ConfigEnv } from 'vite' import { viteMockServe } from 'vite-plugin-mock' import vue from '@vitejs/plugin-vue' export default ({ command }: ConfigEnv): UserConfigExport => { return { plugins: [ vue(), viteMockServe({ mockPath: 'mock', enable: true, }), ], } } ``` - viteMockServe 配置 ```ts { mockPath?: string; ignore?: RegExp | ((fileName: string) => boolean); watchFiles?: boolean; enable?: boolean; ignoreFiles?: string[]; configPath?: string; logger?:boolean; } ``` ### mockPath **type:** string **default:** `mock` 设置模拟.ts 文件的存储文件夹 如果`watchFiles:true`,将监视文件夹中的文件更改。 并实时同步到请求结果 如果 `configPath` 具有值,则无效 ### ignore **type:** `RegExp | ((fileName: string) => boolean)`; **default:** `undefined` 自动读取模拟.ts 文件时,请忽略指定格式的文件 ### watchFiles **type:** `boolean` **default:** `true` 设置是否监视`mockPath`对应的文件夹内文件中的更改 ### enable **type:** `boolean` **default:** true 是否启用 mock 功能 ### configPath **type:** `string` **default:** `vite.mock.config.ts` 设置模拟读取的数据条目。 当文件存在并且位于项目根目录中时,将首先读取并使用该文件。 配置文件返回一个数组 ### logger **type:** `boolean` **default:** `true` 是否在控制台显示请求日志 ## Mock file example `/path/mock` ```ts // test.ts import { MockMethod, MockConfig } from 'vite-plugin-mock' export default [ { url: '/api/get', method: 'get', response: ({ query }) => { return { code: 0, data: { name: 'vben', }, } }, }, { url: '/api/post', method: 'post', timeout: 2000, response: { code: 0, data: { name: 'vben', }, }, }, { url: '/api/text', method: 'post', rawResponse: async (req, res) => { let reqbody = '' await new Promise((resolve) => { req.on('data', (chunk) => { reqbody += chunk }) req.on('end', () => resolve(undefined)) }) res.setHeader('Content-Type', 'text/plain') res.statusCode = 200 res.end(`hello, ${reqbody}`) }, }, ] as MockMethod[] export default function (config: MockConfig) { return [ { url: '/api/text', method: 'post', rawResponse: async (req, res) => { let reqbody = '' await new Promise((resolve) => { req.on('data', (chunk) => { reqbody += chunk }) req.on('end', () => resolve(undefined)) }) res.setHeader('Content-Type', 'text/plain') res.statusCode = 200 res.end(`hello, ${reqbody}`) }, }, ] } ``` ### MockMethod ```ts { // 请求地址 url: string; // 请求方式 method?: MethodType; // 设置超时时间 timeout?: number; // 状态吗 statusCode?:number; // 响应数据(JSON) response?: ((opt: { [key: string]: string; body: Record; query: Record, headers: Record; }) => any) | any; // 响应(非JSON) rawResponse?: (req: IncomingMessage, res: ServerResponse) => void; } ``` ## 在生产环境中的使用 创建`mockProdServer.ts` 文件 ```ts // mockProdServer.ts import { createProdMockServer } from 'vite-plugin-mock/client' // 逐一导入您的mock.ts文件 // 如果使用vite.mock.config.ts,只需直接导入文件 // 可以使用 import.meta.glob功能来进行全部导入 import testModule from '../mock/test' export function setupProdMockServer() { createProdMockServer([...testModule]) } ``` 配置 `vite-plugin-mock` ```ts import { viteMockServe } from 'vite-plugin-mock' import { UserConfigExport, ConfigEnv } from 'vite' export default ({ command }: ConfigEnv): UserConfigExport => { return { plugins: [ viteMockServe({ mockPath: 'mock', // 根据项目配置。可以配置在.env文件 enable: true, }), ], } } ``` ### 示例 **运行示例** ```bash pnpm install # ts example cd ./examples/ts-examples pnpm run serve # js example cd ./examples/js-examples pnpm run serve ``` ## 示例项目 [Vben Admin](https://github.com/anncwb/vue-vben-admin) ## 注意事项 - 无法在 mock.ts 文件中使用 node 模块,否则生产环境将失败 - 模拟数据如果用于生产环境,仅适用于某些测试环境。 不要在正式环境中打开它,以避免不必要的错误。 同时,在生产环境中,它可能会影响正常的 Ajax 请求,例如文件上传/下载失败等。 ## License MIT [npm-img]: https://img.shields.io/npm/v/vite-plugin-mock.svg [npm-url]: https://npmjs.com/package/vite-plugin-mock [node-img]: https://img.shields.io/node/v/vite-plugin-mock.svg [node-url]: https://nodejs.org/en/about/releases/ ================================================ FILE: commitlint.config.js ================================================ module.exports = { extends: ['@commitlint/config-conventional'] } ================================================ FILE: package.json ================================================ { "name": "vite-plugin-mock-monorepo", "version": "2.9.8", "private": true, "description": "A mock plugin for vite", "files": [ "dist", "es" ], "engines": { "node": ">=12.0.0" }, "scripts": { "log": "conventional-changelog -p angular -i CHANGELOG.md -s", "lint:lint-staged": "lint-staged -c ./.husky/lintstagedrc.js", "lint:eslint": "eslint \"src/**/*.{ts,tsx}\" --fix", "prepare": "husky install" }, "keywords": [ "vite", "mock", "hmr" ], "author": "Vben", "license": "MIT", "devDependencies": { "@commitlint/cli": "^17.6.1", "@commitlint/config-conventional": "^17.6.1", "@types/connect": "^3.4.35", "@types/debug": "^4.1.7", "@types/node": "^16.18.23", "@typescript-eslint/eslint-plugin": "^5.58.0", "@typescript-eslint/parser": "^5.58.0", "commitizen": "^4.3.0", "conventional-changelog-cli": "^2.2.2", "eslint": "^8.38.0", "eslint-config-prettier": "^8.8.0", "husky": "^8.0.3", "lint-staged": "^13.2.1", "prettier": "^2.8.7", "rimraf": "^5.0.0", "typescript": "^5.0.4" } } ================================================ FILE: packages/playground/js-example/.gitignore ================================================ node_modules .DS_Store dist *.local ================================================ FILE: packages/playground/js-example/index.html ================================================ Vite App
================================================ FILE: packages/playground/js-example/mock/role.mjs ================================================ export default [ { url: '/api/getRoleById', method: 'get', response: ({ query }) => { console.log('id>>>>>>>>', query.id) return { code: 0, message: 'ok', data: { roleName: 'admin', roleValue: 'admin1', }, } }, }, ] ================================================ FILE: packages/playground/js-example/mock/user.js ================================================ export default [ { url: '/api/createUser', method: 'post', response: ({ body }) => { console.log('body>>>>>>>>', body) return { code: 0, message: 'ok', data: null, } }, }, ] ================================================ FILE: packages/playground/js-example/package.json ================================================ { "name": "ts-example", "version": "0.0.0", "private": true, "scripts": { "dev": "cross-env NODE_ENV=development vite", "build": "cross-env NODE_ENV=production vite build " }, "dependencies": { "axios": "^1.3.5", "element-plus": "^2.3.3", "mockjs": "^1.1.0", "vue": "^3.2.47" }, "devDependencies": { "@vitejs/plugin-vue": "^4.1.0", "@vue/compiler-sfc": "^3.2.47", "cross-env": "^7.0.3", "vite": "^4.2.1", "vite-plugin-mock": "workspace:*" } } ================================================ FILE: packages/playground/js-example/src/App.vue ================================================ ================================================ FILE: packages/playground/js-example/src/main.js ================================================ import { createApp } from 'vue' import App from './App.vue' import ElementPlus from 'element-plus' import 'element-plus/theme-chalk/index.css' createApp(App).use(ElementPlus).mount('#app') ================================================ FILE: packages/playground/js-example/src/mockProdServer.js ================================================ import { createProdMockServer } from '../../../es/createProdMockServer' import roleMock from '../mock/role' import userMock from '../mock/user' export function setupProdMockServer() { createProdMockServer([...roleMock, ...userMock]) } ================================================ FILE: packages/playground/js-example/vite.config.js ================================================ import { viteMockServe } from 'vite-plugin-mock' import vue from '@vitejs/plugin-vue' export default ({ command }) => { let prodMock = true return { plugins: [ vue(), viteMockServe({ mockPath: 'mock', enable: true, }), ], } } ================================================ FILE: packages/playground/ts-example/.gitignore ================================================ node_modules .DS_Store dist *.local ================================================ FILE: packages/playground/ts-example/index.html ================================================ Vite App
================================================ FILE: packages/playground/ts-example/mock/define.ts ================================================ import type { MockConfig } from 'vite-plugin-mock' export default (config: MockConfig) => { return [ { url: '/api/testRestful/:id', method: 'post', response: ({ query, body }) => { console.log('query>>>>>>>>', query) console.log('body>>>>>>>>', body) return { code: 0, message: 'ok', data: { roleName: 'admin', roleValue: 'admin', }, } }, }, ] } ================================================ FILE: packages/playground/ts-example/mock/dep/role.ts ================================================ import type { MockMethod } from 'vite-plugin-mock' export default [ { url: '/api/getRoleById', method: 'get', response: ({ query }) => { console.log('id>>>>>>>>', query.id) return { code: 0, message: 'ok', data: { roleName: 'admin', roleValue: 'admin', }, } }, }, { url: '/api/testRestful/:id', method: 'get', response: ({ query }) => { console.log('id>>>>>>>>', query.id) return { code: 0, message: 'ok', data: { roleName: 'admin', roleValue: 'admin', }, } }, }, ] as MockMethod[] ================================================ FILE: packages/playground/ts-example/mock/user.ts ================================================ import type { MockConfig } from 'vite-plugin-mock' export default (config?: MockConfig) => { return [ { url: '/api/createUser', method: 'post', response: ({ body, query }) => { console.log('body>>>>>>>>', body) console.log('query>>>>>>>>', query) return { code: 0, message: 'ok', data: { a: 21, 'import.meta.url': import.meta.url }, } }, }, ] } ================================================ FILE: packages/playground/ts-example/package.json ================================================ { "name": "ts-example", "version": "0.0.0", "private": true, "scripts": { "dev": "cross-env NODE_ENV=development vite", "build": "cross-env NODE_ENV=production vite build " }, "dependencies": { "axios": "^1.3.5", "element-plus": "^2.3.3", "find-up": "^6.3.0", "mockjs": "^1.1.0", "vue": "^3.2.47" }, "devDependencies": { "@vitejs/plugin-vue": "^4.1.0", "@vue/compiler-sfc": "^3.2.47", "cross-env": "^7.0.3", "typescript": "^5.0.4", "vite": "^4.2.1", "vite-plugin-mock": "workspace:*" } } ================================================ FILE: packages/playground/ts-example/shim-vue.ts ================================================ declare module '*.vue' { import { ComponentOptions } from 'vue' const component: ComponentOptions export default component } ================================================ FILE: packages/playground/ts-example/src/App.vue ================================================ ================================================ FILE: packages/playground/ts-example/src/main.ts ================================================ import { createApp } from 'vue' import App from './App.vue' import ElementPlus from 'element-plus' import 'element-plus/theme-chalk/index.css' createApp(App).use(ElementPlus).mount('#app') // production mock server if (process.env.NODE_ENV === 'production') { import('./mockProdServer').then(({ setupProdMockServer }) => { setupProdMockServer() }) } ================================================ FILE: packages/playground/ts-example/src/mockProdServer.ts ================================================ import { createProdMockServer } from 'vite-plugin-mock/client' import roleMock from '../mock/dep/role' import userMockFn from '../mock/user' export async function setupProdMockServer() { const mockModules = [...roleMock, ...userMockFn()] createProdMockServer(mockModules) } ================================================ FILE: packages/playground/ts-example/tsconfig.json ================================================ { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": "node", "strict": true, "forceConsistentCasingInFileNames": true, "allowSyntheticDefaultImports": true, "strictFunctionTypes": false, "jsx": "preserve", "baseUrl": ".", "allowJs": true, "sourceMap": true, "esModuleInterop": true, "resolveJsonModule": true, "noUnusedLocals": true, "noUnusedParameters": true, "experimentalDecorators": true, "lib": ["dom", "esnext"], "types": ["vite/client"], "typeRoots": ["./node_modules/@types/", "./types"], "incremental": true, "noImplicitAny": false, "skipLibCheck": true }, "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], "exclude": ["node_modules", "dist", "**/*.js"] } ================================================ FILE: packages/playground/ts-example/vite.config.ts ================================================ import { viteMockServe } from 'vite-plugin-mock' import { UserConfigExport } from 'vite' import vue from '@vitejs/plugin-vue' export default (): UserConfigExport => { return { plugins: [ vue(), viteMockServe({ mockPath: 'mock', enable: true, logger: true, }), ], } } ================================================ FILE: packages/vite-plugin-mock/CHANGELOG.md ================================================ ## [2.9.8](https://github.com/anncwb/vite-plugin-mock/compare/v2.9.0...v2.9.8) (2023-04-16) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/anncwb/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/anncwb/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - error handle, fix [#39](https://github.com/anncwb/vite-plugin-mock/issues/39) ([874318c](https://github.com/anncwb/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/anncwb/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/anncwb/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) - inappropriate type annotation ([#90](https://github.com/anncwb/vite-plugin-mock/issues/90)) ([a3fc4aa](https://github.com/anncwb/vite-plugin-mock/commit/a3fc4aab3dd1864f640918516c10d7d1530f5d90)) - typo, close [#42](https://github.com/anncwb/vite-plugin-mock/issues/42) ([5b4e946](https://github.com/anncwb/vite-plugin-mock/commit/5b4e9469060109a2a28c079eec8384fe654be68e)) ### Features - **prod:** response 在 prod 模式下入参对象加上 url ([#83](https://github.com/anncwb/vite-plugin-mock/issues/83)) ([cd0b86f](https://github.com/anncwb/vite-plugin-mock/commit/cd0b86fce20228094cf18be14194498a2cbd490e)) - **server:** add this for response, rawResponse function ([#43](https://github.com/anncwb/vite-plugin-mock/issues/43)) ([2f4d6d2](https://github.com/anncwb/vite-plugin-mock/commit/2f4d6d2984c7fe15236cb8b0d2ec5479930d5668)) ## [2.9.6](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.6) (2021-08-23) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/anncwb/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/anncwb/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - error handle, fix [#39](https://github.com/anncwb/vite-plugin-mock/issues/39) ([874318c](https://github.com/anncwb/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/anncwb/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/anncwb/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) - typo, close [#42](https://github.com/anncwb/vite-plugin-mock/issues/42) ([5b4e946](https://github.com/anncwb/vite-plugin-mock/commit/5b4e9469060109a2a28c079eec8384fe654be68e)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) - **server:** add this for response, rawResponse function ([#43](https://github.com/anncwb/vite-plugin-mock/issues/43)) ([2f4d6d2](https://github.com/anncwb/vite-plugin-mock/commit/2f4d6d2984c7fe15236cb8b0d2ec5479930d5668)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.9.5](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.5) (2021-08-23) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/anncwb/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/anncwb/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - error handle, fix [#39](https://github.com/anncwb/vite-plugin-mock/issues/39) ([874318c](https://github.com/anncwb/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/anncwb/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/anncwb/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) - **server:** add this for response, rawResponse function ([#43](https://github.com/anncwb/vite-plugin-mock/issues/43)) ([2f4d6d2](https://github.com/anncwb/vite-plugin-mock/commit/2f4d6d2984c7fe15236cb8b0d2ec5479930d5668)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.9.4](https://github.com/anncwb/vite-plugin-mock/compare/v2.9.0...v2.9.4) (2021-08-01) ### Bug Fixes - can't update in real time, fix [#40](https://github.com/anncwb/vite-plugin-mock/issues/40) ([f25c6ac](https://github.com/anncwb/vite-plugin-mock/commit/f25c6ac8544991457368746bf6ec5fdfd8b4e083)) - error handle, fix [#39](https://github.com/anncwb/vite-plugin-mock/issues/39) ([874318c](https://github.com/anncwb/vite-plugin-mock/commit/874318ce399dc78c33d91161b73e3ced7bb6e9b6)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - fix node version ([#38](https://github.com/anncwb/vite-plugin-mock/issues/38)) ([f91dea1](https://github.com/anncwb/vite-plugin-mock/commit/f91dea1be943aa1145727bfecd273ef45cdff8e9)) ## [2.9.3](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.3) (2021-07-18) ### Bug Fixes - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.9.2](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.2) (2021-07-18) ### Bug Fixes - ensure file changes take effect,fix [#36](https://github.com/anncwb/vite-plugin-mock/issues/36) ([353aa9d](https://github.com/anncwb/vite-plugin-mock/commit/353aa9db67483072a3d60b6bf3c99736563bba43)) - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - fix js parsing error ([1dbee45](https://github.com/anncwb/vite-plugin-mock/commit/1dbee452ec7d90b07ac86ce8530430e864589ab5)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.9.1](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.1) (2021-07-06) ### Bug Fixes - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - fix js parsing error ([d2746b6](https://github.com/anncwb/vite-plugin-mock/commit/d2746b6d788cdd304cac8512afa743b01edbd479)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) # [2.9.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.9.0) (2021-07-05) ### Bug Fixes - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([4cb55f8](https://github.com/anncwb/vite-plugin-mock/commit/4cb55f87def1e3edf07937ce48b0cfc594f2b88d)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([4625e59](https://github.com/anncwb/vite-plugin-mock/commit/4625e59429b4fc06ff4f911d681ee4999661c3ec)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) # [2.8.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.8.0) (2021-06-16) ### Bug Fixes - ensure that the post with parameters are matched,fix [#29](https://github.com/anncwb/vite-plugin-mock/issues/29) ([bfed256](https://github.com/anncwb/vite-plugin-mock/commit/bfed256bff42e2348b30a6b31746854b18fc90b8)) - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - remove supportTs, change to automatic judgment ([a341c7d](https://github.com/anncwb/vite-plugin-mock/commit/a341c7d5b2de153593c0d1f5dab00b1b730a6819)) - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.7.2](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.7.2) (2021-06-10) ### Bug Fixes - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - make sure ignore matches the file correctly ([b612a09](https://github.com/anncwb/vite-plugin-mock/commit/b612a0934b7dcaae423450a56139cc9b9749c43e)) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) ## [2.7.1](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.7.1) (2021-06-09) ### Bug Fixes - improve path matching logic, fix [#25](https://github.com/anncwb/vite-plugin-mock/issues/25) ([5079e4b](https://github.com/anncwb/vite-plugin-mock/commit/5079e4ba1c713aaba2facc87dfb289ea0916c231)) - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) - support node12 ([fdfed60](https://github.com/anncwb/vite-plugin-mock/commit/fdfed60b6d8859bdcf8292c30859101f47d758b5)) ### Features - response return url ([#27](https://github.com/anncwb/vite-plugin-mock/issues/27)) ([de9ed27](https://github.com/anncwb/vite-plugin-mock/commit/de9ed276b61c18cdfe0509df21921bc3ddf9d767)) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) # [2.6.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.5.0...v2.6.0) (2021-05-29) ### Bug Fixes - loss request headers in PROD mode ([#23](https://github.com/anncwb/vite-plugin-mock/issues/23)) ([76302df](https://github.com/anncwb/vite-plugin-mock/commit/76302df9cc5a23fe0ccd001787bffbb4c012cc83)), closes [#15](https://github.com/anncwb/vite-plugin-mock/issues/15) ### Reverts - revert 2.5.0, fix [#22](https://github.com/anncwb/vite-plugin-mock/issues/22) ([d5ac0d6](https://github.com/anncwb/vite-plugin-mock/commit/d5ac0d68a67f4e4cc568ef1eff12f2ba425553e8)) # [2.5.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.4.0...v2.5.0) (2021-04-06) ### Bug Fixes - production xhr ([6c94783](https://github.com/anncwb/vite-plugin-mock/commit/6c94783f07b27c6ac58a4642c0e7eddf34b06f1f)) - **eslint warn:** fix some warn ([b44c13b](https://github.com/anncwb/vite-plugin-mock/commit/b44c13b766cda0ee310071e9febeb48d73ef7bde)) - empty TS file in mock folder is error ([669b804](https://github.com/anncwb/vite-plugin-mock/commit/669b804df31f537bf6985b56972b32dd11e20504)) ### Features - add rawResponse option to MockMethod ([#17](https://github.com/anncwb/vite-plugin-mock/issues/17)) ([24775f9](https://github.com/anncwb/vite-plugin-mock/commit/24775f9d7b14d024d90cd36c850a00634341927f)), closes [#16](https://github.com/anncwb/vite-plugin-mock/issues/16) ### Performance Improvements - perf code ([98b9dbc](https://github.com/anncwb/vite-plugin-mock/commit/98b9dbc64f5c6da815a1f29c6b588fddd5189370)) ## [2.4.1](https://github.com/anncwb/vite-plugin-mock/compare/v2.4.0...v2.4.1) (2021-03-30) ### Bug Fixes - empty TS file in mock folder is error ([669b804](https://github.com/anncwb/vite-plugin-mock/commit/669b804df31f537bf6985b56972b32dd11e20504)) ### Performance Improvements - perf code ([98b9dbc](https://github.com/anncwb/vite-plugin-mock/commit/98b9dbc64f5c6da815a1f29c6b588fddd5189370)) # [2.4.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.3.0...v2.4.0) (2021-03-25) ### Features - response return headers, close [#10](https://github.com/anncwb/vite-plugin-mock/issues/10) ([bcb7abd](https://github.com/anncwb/vite-plugin-mock/commit/bcb7abd98e8726af6f1721ad021c06028b1ffca7)) ## [2.2.4](https://github.com/anncwb/vite-plugin-mock/compare/v2.2.3...v2.2.4) (2021-03-10) ### Features - support post restful close [#7](https://github.com/anncwb/vite-plugin-mock/issues/7) ([70b51e8](https://github.com/anncwb/vite-plugin-mock/commit/70b51e8738e41a7011e38e942dd2a136e450ae9f)) ## [2.2.3](https://github.com/anncwb/vite-plugin-mock/compare/v2.2.0...v2.2.3) (2021-03-10) ### Bug Fixes - ensure that the URLs of different request methods cannot match close [#6](https://github.com/anncwb/vite-plugin-mock/issues/6) ([361a3eb](https://github.com/anncwb/vite-plugin-mock/commit/361a3eb62874f7a6dce8cdc8add4487302c3ee04)) ### Features - support restful api close [#4](https://github.com/anncwb/vite-plugin-mock/issues/4) ([236393e](https://github.com/anncwb/vite-plugin-mock/commit/236393ef551de32fbba62fbb27f678d4782568ec)) ## [2.2.1](https://github.com/anncwb/vite-plugin-mock/compare/v2.2.0...v2.2.1) (2021-03-09) ### Features - support restful api close [#4](https://github.com/anncwb/vite-plugin-mock/issues/4) ([7a35b1a](https://github.com/anncwb/vite-plugin-mock/commit/7a35b1a3af3bfa8623f1d24f53e71928df20b69b)) # [2.2.0](https://github.com/anncwb/vite-plugin-mock/compare/v2.1.5...v2.2.0) (2021-03-02) ### Features - add logger option ([66a75ab](https://github.com/anncwb/vite-plugin-mock/commit/66a75ab0ee5a7c8e03987e74f15b50aedd1cc29f)) ## [2.1.5](https://github.com/anncwb/vite-plugin-mock/compare/v2.0.0-beta.1...v2.1.5) (2021-02-23) ### Bug Fixes - correct sourcemap ([2140987](https://github.com/anncwb/vite-plugin-mock/commit/21409876876b845b18b5b006e98292138870a922)) - dev sourcemap ([5834b4f](https://github.com/anncwb/vite-plugin-mock/commit/5834b4f621b25371a7b0246a48fb83b9761afeed)) - fix post proxy error ([d3ae41e](https://github.com/anncwb/vite-plugin-mock/commit/d3ae41e18a5e7adae504457165ba7b34b8ebff6f)) ### Features - support sourcemap ([8c3cd9d](https://github.com/anncwb/vite-plugin-mock/commit/8c3cd9d78a9bd7f87dc7900e9bfe6c753ff3b11f)) ### Performance Improvements - imporve request log ([f9353fd](https://github.com/anncwb/vite-plugin-mock/commit/f9353fdf8149665f984729ab3c7a6749022cfdaf)) # [2.0.0-beta.1](https://github.com/anncwb/vite-plugin-mock/compare/2.0.0-beta.1...v2.0.0-beta.1) (2021-01-03) ### Bug Fixes - Fix local development post request proxy to https ([7965604](https://github.com/anncwb/vite-plugin-mock/commit/79656046377f501da796d1be9752522a2203d69b)) - remove unnecessary and wrong usage of "try catch" ([815abde](https://github.com/anncwb/vite-plugin-mock/commit/815abde26f8f9a19322916ae01a9896a9aced33a)) ### Features - add request time ([ccbb14a](https://github.com/anncwb/vite-plugin-mock/commit/ccbb14ad623e6549781e5e902819f830a291f13f)) ## [1.0.2](https://github.com/anncwb/vite-plugin-mock/compare/1.0.1...1.0.2) (2020-09-14) ### Features - add examples ([2c5a86b](https://github.com/anncwb/vite-plugin-mock/commit/2c5a86bb75e39b6c7c9e08b1691c0541aeb104d9)) ## [1.0.1](https://github.com/anncwb/vite-plugin-mock/compare/58ad7cd57e3fd0daa92e0fc59c00e09cf6ba45ad...1.0.1) (2020-09-14) ### Features - add supportTs options,Support es6 and commonjs modules in .js folder ([37f83f5](https://github.com/anncwb/vite-plugin-mock/commit/37f83f54c3a34e049f967b0db0ac2ade401cbf58)) ### Performance Improvements - Replace typescript plug-in with a faster esbuild plug-in ([58ad7cd](https://github.com/anncwb/vite-plugin-mock/commit/58ad7cd57e3fd0daa92e0fc59c00e09cf6ba45ad)) ================================================ FILE: packages/vite-plugin-mock/build.config.ts ================================================ import { defineBuildConfig } from 'unbuild' export default defineBuildConfig({ clean: true, entries: ['src/index', 'src/client'], declaration: true, rollup: { emitCJS: true, }, }) ================================================ FILE: packages/vite-plugin-mock/package.json ================================================ { "name": "vite-plugin-mock", "version": "3.0.2", "description": "A mock plugin for vite", "main": "dist/index.cjs", "module": "dist/index.mjs", "types": "dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.cjs" }, "./client": { "types": "./dist/client.d.ts", "import": "./dist/client.mjs", "require": "./dist/client.cjs" } }, "files": [ "dist" ], "type": "module", "engines": { "node": ">=16.0.0" }, "scripts": { "clean": "rimraf dist && rimraf es", "dev": "unbuild --stub", "build": "unbuild", "log": "conventional-changelog -p angular -i CHANGELOG.md -s", "prepublishOnly": "npm run build" }, "keywords": [ "vite", "mock", "hmr" ], "author": "Vben", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/anncwb/vite-plugin-mock", "directory": "packages/vite-plugin-mock" }, "bugs": { "url": "https://github.com/anncwb/vite-plugin-mock/issues" }, "homepage": "https://github.com/anncwb/vite-plugin-mock/tree/master/#readme", "dependencies": { "bundle-require": "^4.0.1", "chokidar": "^3.5.3", "connect": "^3.7.0", "debug": "^4.3.4", "fast-glob": "^3.2.12", "path-to-regexp": "^6.2.1", "picocolors": "^1.0.0" }, "peerDependencies": { "mockjs": ">=1.1.0", "vite": ">=4.0.0", "esbuild": ">=0.17" }, "devDependencies": { "@types/mockjs": "^1.0.7", "@types/connect": "^3.4.35", "@types/debug": "^4.1.7", "@types/node": "^16.18.23", "mockjs": "^1.1.0", "rimraf": "^5.0.0", "tsup": "6.7.0", "typescript": "^5.0.4", "unbuild": "^1.2.1", "vite": "4.2.1" } } ================================================ FILE: packages/vite-plugin-mock/src/client.ts ================================================ /* eslint-disable */ import type { MockMethod } from './types' export async function createProdMockServer(mockList: any[]) { const Mock: any = await import('mockjs') const { pathToRegexp } = await import('path-to-regexp') Mock.XHR.prototype.__send = Mock.XHR.prototype.send Mock.XHR.prototype.send = function () { if (this.custom.xhr) { this.custom.xhr.withCredentials = this.withCredentials || false if (this.responseType) { this.custom.xhr.responseType = this.responseType } } if (this.custom.requestHeaders) { const headers: any = {} for (let k in this.custom.requestHeaders) { headers[k.toString().toLowerCase()] = this.custom.requestHeaders[k] } this.custom.options = Object.assign({}, this.custom.options, { headers }) } this.__send.apply(this, arguments) } Mock.XHR.prototype.proxy_open = Mock.XHR.prototype.open Mock.XHR.prototype.open = function () { let responseType = this.responseType this.proxy_open(...arguments) if (this.custom.xhr) { if (responseType) { this.custom.xhr.responseType = responseType } } } for (const { url, method, response, timeout } of mockList) { __setupMock__(Mock, timeout) Mock.mock( pathToRegexp(url, undefined, { end: false }), method || 'get', __XHR2ExpressReqWrapper__(Mock, response), ) } } function __param2Obj__(url: string) { const search = url.split('?')[1] if (!search) { return {} } return JSON.parse( '{"' + decodeURIComponent(search) .replace(/"/g, '\\"') .replace(/&/g, '","') .replace(/=/g, '":"') .replace(/\+/g, ' ') + '"}', ) } function __XHR2ExpressReqWrapper__(_Mock: any, handle: (d: any) => any) { return function (options: any) { let result = null if (typeof handle === 'function') { const { body, type, url, headers } = options let b = body try { b = JSON.parse(body) } catch {} result = handle({ method: type, body: b, query: __param2Obj__(url), headers, }) } else { result = handle } return _Mock.mock(result) } } function __setupMock__(mock: any, timeout = 0) { timeout && mock.setup({ timeout, }) } export function defineMockModule( fn: (config: { env: Record mode: string command: 'build' | 'serve' }) => Promise | MockMethod[], ) { return fn } ================================================ FILE: packages/vite-plugin-mock/src/createMockServer.ts ================================================ import type { ViteMockOptions, MockMethod, Recordable, RespThisType } from './types' import path from 'node:path' import fs from 'node:fs' import chokidar from 'chokidar' import colors from 'picocolors' import url from 'url' import fg from 'fast-glob' import Mock from 'mockjs' import { pathToRegexp, match } from 'path-to-regexp' import { isArray, isFunction, sleep, isRegExp, isAbsPath } from './utils' import { IncomingMessage, NextHandleFunction } from 'connect' import { bundleRequire, GetOutputFile, JS_EXT_RE } from 'bundle-require' import type { ResolvedConfig } from 'vite' export let mockData: MockMethod[] = [] export async function createMockServer( opt: ViteMockOptions = { mockPath: 'mock', configPath: 'vite.mock.config' }, config: ResolvedConfig, ) { opt = { mockPath: 'mock', watchFiles: true, configPath: 'vite.mock.config.ts', logger: true, cors: true, ...opt, } if (mockData.length > 0) return mockData = await getMockConfig(opt, config) await createWatch(opt, config) } // request match export async function requestMiddleware(opt: ViteMockOptions) { const { logger = true } = opt const middleware: NextHandleFunction = async (req, res, next) => { let queryParams: { query?: { [key: string]: any } pathname?: string | null } = {} if (req.url) { queryParams = url.parse(req.url, true) } const reqUrl = queryParams.pathname const matchRequest = mockData.find((item) => { if (!reqUrl || !item || !item.url) { return false } if (item.method && item.method.toUpperCase() !== req.method) { return false } return pathToRegexp(item.url).test(reqUrl) }) if (matchRequest) { const isGet = req.method && req.method.toUpperCase() === 'GET' const { response, rawResponse, timeout, statusCode, url } = matchRequest if (timeout) { await sleep(timeout) } const urlMatch = match(url, { decode: decodeURIComponent }) let query = queryParams.query as any if (reqUrl) { if ((isGet && JSON.stringify(query) === '{}') || !isGet) { const params = (urlMatch(reqUrl) as any).params if (JSON.stringify(params) !== '{}') { query = (urlMatch(reqUrl) as any).params || {} } else { query = queryParams.query || {} } } } const self: RespThisType = { req, res, parseJson: parseJson.bind(null, req) } if (isFunction(rawResponse)) { await rawResponse.bind(self)(req, res) } else { const body = await parseJson(req) res.setHeader('Content-Type', 'application/json') if (opt) { res.setHeader('Access-Control-Allow-Credentials', true) res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*') } res.statusCode = statusCode || 200 const mockResponse = isFunction(response) ? response.bind(self)({ url: req.url as any, body, query, headers: req.headers }) : response res.end(JSON.stringify(Mock.mock(mockResponse))) } logger && loggerOutput('request invoke', req.url!) return } next() } return middleware } // create watch mock function createWatch(opt: ViteMockOptions, config: ResolvedConfig) { const { configPath, logger, watchFiles } = opt if (!watchFiles) { return } const { absConfigPath, absMockPath } = getPath(opt) if (process.env.VITE_DISABLED_WATCH_MOCK === 'true') { return } const watchDir = [] const exitsConfigPath = fs.existsSync(absConfigPath) exitsConfigPath && configPath ? watchDir.push(absConfigPath) : watchDir.push(absMockPath) const watcher = chokidar.watch(watchDir, { ignoreInitial: true, // ignore files generated by `bundle require` ignored: '**/_*.bundled_*.(mjs|cjs)', }) watcher.on('all', async (event, file) => { logger && loggerOutput(`mock file ${event}`, file) mockData = await getMockConfig(opt, config) }) } // clear cache function cleanRequireCache(opt: ViteMockOptions) { if (typeof require === 'undefined' || !require.cache) { return } const { absConfigPath, absMockPath } = getPath(opt) Object.keys(require.cache).forEach((file) => { if (file === absConfigPath || file.indexOf(absMockPath) > -1) { delete require.cache[file] } }) } function parseJson(req: IncomingMessage): Promise { return new Promise((resolve) => { let jsonStr: Recordable = {} let str = '' req.on('data', function (chunk) { str += chunk }) req.on('end', () => { try { // json jsonStr = JSON.parse(str) } catch (e) { // x-www-form-urlencoded const params = new URLSearchParams(str) const body: Recordable = {} params.forEach((value, key) => { body[key] = value }) jsonStr = body } resolve(jsonStr) return }) }) } // load mock .ts files and watch async function getMockConfig(opt: ViteMockOptions, config: ResolvedConfig) { const { absConfigPath, absMockPath } = getPath(opt) const { ignore, configPath, logger } = opt let ret: MockMethod[] = [] if (configPath && fs.existsSync(absConfigPath)) { logger && loggerOutput(`load mock data from`, absConfigPath) ret = await resolveModule(absConfigPath, config) return ret } const mockFiles = fg .sync(`**/*.{ts,mjs,js}`, { cwd: absMockPath, }) .filter((item) => { if (!ignore) { return true } if (isFunction(ignore)) { return !ignore(item) } if (isRegExp(ignore)) { return !ignore.test(path.basename(item)) } return true }) try { ret = [] const resolveModulePromiseList = [] for (let index = 0; index < mockFiles.length; index++) { const mockFile = mockFiles[index] resolveModulePromiseList.push(resolveModule(path.join(absMockPath, mockFile), config)) } const loadAllResult = await Promise.all(resolveModulePromiseList) for (const resultModule of loadAllResult) { let mod = resultModule if (!isArray(mod)) { mod = [mod] } ret = [...ret, ...mod] } } catch (error: any) { loggerOutput(`mock reload error`, error) ret = [] } return ret } // fixed file generation format // use a random path to avoid import cache const getOutputFile: GetOutputFile = (filepath, format) => { const dirname = path.dirname(filepath) const basename = path.basename(filepath) const randomname = `${Date.now()}_${Math.random().toString(36).substring(2, 15)}` return path.resolve( dirname, `_${basename.replace(JS_EXT_RE, `.bundled_${randomname}.${format === 'esm' ? 'mjs' : 'cjs'}`)}`, ) } // Inspired by vite // support mock .ts files async function resolveModule(p: string, config: ResolvedConfig): Promise { const mockData = await bundleRequire({ filepath: p, getOutputFile, }) let mod = mockData.mod.default || mockData.mod if (isFunction(mod)) { mod = await mod({ env: config.env, mode: config.mode, command: config.command }) } return mod } // get custom config file path and mock dir path function getPath(opt: ViteMockOptions) { const { mockPath, configPath } = opt const cwd = process.cwd() const absMockPath = isAbsPath(mockPath) ? mockPath! : path.join(cwd, mockPath || '') const absConfigPath = path.join(cwd, configPath || '') return { absMockPath, absConfigPath, } } function loggerOutput(title: string, msg: string, type: 'info' | 'error' = 'info') { const tag = type === 'info' ? colors.cyan(`[vite:mock]`) : colors.red(`[vite:mock-server]`) return console.log( `${colors.dim(new Date().toLocaleTimeString())} ${tag} ${colors.green(title)} ${colors.dim( msg, )}`, ) } ================================================ FILE: packages/vite-plugin-mock/src/index.ts ================================================ ;(async () => { try { await import('mockjs') } catch (e) { throw new Error('vite-plugin-vue-mock requires mockjs to be present in the dependency tree.') } })() import type { ViteMockOptions } from './types' import type { Plugin } from 'vite' import { ResolvedConfig } from 'vite' import { createMockServer, requestMiddleware } from './createMockServer' export function viteMockServe(opt: ViteMockOptions = {}): Plugin { let isDev = false let config: ResolvedConfig return { name: 'vite:mock', enforce: 'pre' as const, configResolved(resolvedConfig) { config = resolvedConfig isDev = config.command === 'serve' isDev && createMockServer(opt, config) }, configureServer: async ({ middlewares }) => { const { enable = isDev } = opt if (!enable) { return } const middleware = await requestMiddleware(opt) middlewares.use(middleware) }, } } export * from './types' ================================================ FILE: packages/vite-plugin-mock/src/types.ts ================================================ import { IncomingMessage, ServerResponse } from 'http' export interface ViteMockOptions { mockPath?: string configPath?: string ignore?: RegExp | ((fileName: string) => boolean) watchFiles?: boolean enable?: boolean logger?: boolean cors?: boolean } export interface RespThisType { req: IncomingMessage res: ServerResponse parseJson: () => any } export type MethodType = 'get' | 'post' | 'put' | 'delete' | 'patch' export type Recordable = Record export declare interface MockMethod { url: string method?: MethodType timeout?: number statusCode?: number response?: | (( this: RespThisType, opt: { url: Recordable; body: Recordable; query: Recordable; headers: Recordable }, ) => any) | any rawResponse?: (this: RespThisType, req: IncomingMessage, res: ServerResponse) => void } export interface MockConfig { env: Record mode: string command: 'build' | 'serve' } ================================================ FILE: packages/vite-plugin-mock/src/utils.ts ================================================ import fs from 'fs' const toString = Object.prototype.toString export function is(val: unknown, type: string) { return toString.call(val) === `[object ${type}]` } // eslint-disable-next-line export function isFunction(val: unknown): val is T { return is(val, 'Function') || is(val, 'AsyncFunction') } export function isArray(val: any): val is Array { return val && Array.isArray(val) } export function isRegExp(val: unknown): val is RegExp { return is(val, 'RegExp') } export function isAbsPath(path: string | undefined) { if (!path) { return false } // Windows 路径格式:C:\ 或 \\ 开头,或已含盘符(D:\path\to\file) if (/^([a-zA-Z]:\\|\\\\|(?:\/|\uFF0F){2,})/.test(path)) { return true } // Unix/Linux 路径格式:/ 开头 return /^\/[^/]/.test(path) } export function sleep(time: number) { return new Promise((resolve) => { setTimeout(() => { resolve('') }, time) }) } ================================================ FILE: packages/vite-plugin-mock/tsconfig.json ================================================ { "compilerOptions": { "target": "esnext", "moduleResolution": "node", "strict": true, "declaration": true, "noUnusedLocals": true, "esModuleInterop": true, "outDir": "dist", "module": "commonjs", "lib": ["ESNext"], "types": ["vite/client", "node"], "sourceMap": false, "noEmitOnError": true }, "include": ["src", "tests"], "exclude": ["**/dist/**", "**/node_modules/**"] } ================================================ FILE: pnpm-workspace.yaml ================================================ packages: - 'packages/*' - 'packages/playground/*' ================================================ FILE: prettier.config.js ================================================ module.exports = { printWidth: 100, tabWidth: 2, useTabs: false, semi: false, singleQuote: true, trailingComma: 'all', } ================================================ FILE: tests/index.spec.ts ================================================ // import { discreteDir } from '../src/index'; // test('discreteDir Not included /', () => { // const { fileName, dirName } = discreteDir('file.svg'); // expect(fileName).toBe('file.svg'); // expect(dirName).toBe(''); // }); ================================================ FILE: tsconfig.es.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "module": "esnext", "outDir": "es" }, "include": ["./src/createProdMockServer.ts"], "exclude": ["**/dist/**", "**/node_modules/**"] } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "target": "esnext", "moduleResolution": "node", "strict": true, "declaration": true, "noUnusedLocals": true, "esModuleInterop": true, "outDir": "dist", "module": "commonjs", "lib": ["ESNext"], "types": ["vite/client", "node"], "sourceMap": false, "noEmitOnError": true }, "include": ["src", "tests"], "exclude": ["**/dist/**", "**/node_modules/**"] }