|
| 1 | +/* eslint-env node */ |
| 2 | +const path = require('path'); |
| 3 | +const fs = require('fs'); |
| 4 | +const { getAppRoot, resolve, formatPath } = require('../lib/misc'); |
| 5 | +const pluginName = 'vite-plugin-http-request-mock'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Use regexp to test against path which treats '\' as '/' on windows. |
| 9 | + * |
| 10 | + * @param {RegExp} regexp |
| 11 | + * @param {string} assetFile |
| 12 | + */ |
| 13 | +const testPath = (regexp, assetFile) => { |
| 14 | + return regexp.test(assetFile) || (process.platform === 'win32' && regexp.test(formatPath(assetFile))); |
| 15 | +}; |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {regexp} appEntry Required, app entry file which mock dependencies will be injected into. |
| 19 | + * @param {string} mockDir Required, mock directory which contains all mock files & the runtime mock config entry file. |
| 20 | + * @param {boolean} enable Optional, whether or not to enable this plugin. Default: true |
| 21 | + * @param {boolean} debug Optional, output some debug logs. Default: false |
| 22 | + */ |
| 23 | +const vitePluginHttpRequestMock = ({ appEntry, mockDir, enable = true, debug = false}) => { |
| 24 | + if (!(appEntry instanceof RegExp)) { |
| 25 | + throw new Error(`${pluginName} expects [appEntry] to be a valid RegExp Object.`); |
| 26 | + } |
| 27 | + |
| 28 | + const absoluteDir = resolve(path.isAbsolute(mockDir) ? mockDir : path.resolve(getAppRoot(), mockDir)); |
| 29 | + if (!mockDir || !fs.existsSync(absoluteDir)) { |
| 30 | + throw new Error(`${pluginName} expects [mockDir] to be a valid directory.`); |
| 31 | + } |
| 32 | + const runtimeFile = resolve(absoluteDir, '.runtime.js'); |
| 33 | + if (!fs.existsSync(runtimeFile)) { |
| 34 | + throw new Error(`${pluginName} can not find the runtime mock config entry file: ${runtimeFile}.`); |
| 35 | + } |
| 36 | + |
| 37 | + return { |
| 38 | + name: pluginName, |
| 39 | + transform(code, id) { |
| 40 | + if (!enable) return; |
| 41 | + |
| 42 | + const match = testPath(appEntry, id); |
| 43 | + if (debug) { |
| 44 | + console.log(`${appEntry.toString()} -> ${id} ${match ? '-> hit!!!' : ''}`); |
| 45 | + } |
| 46 | + if (match) { |
| 47 | + return `import "${runtimeFile}"; // runtime mock config entry file.\n${code}`; |
| 48 | + } |
| 49 | + }, |
| 50 | + }; |
| 51 | +}; |
| 52 | + |
| 53 | +module.exports = vitePluginHttpRequestMock; |
0 commit comments