|
| 1 | +import { existsSync } from 'node:fs' |
| 2 | +import { dirname, resolve } from 'node:path' |
1 | 3 | import { defineConfig } from 'vite-plus' |
2 | 4 |
|
| 5 | +const RELEASE_IMPORTER_PATH = '../../_build/js/release/build/moonscratch.js' |
| 6 | +const RELEASE_BINDING_PATH = '../../_build/js/release/build/moonscratch.js' |
| 7 | +const DEBUG_BINDING_PATH = '../../_build/js/debug/build/moonscratch.js' |
| 8 | +const DEBUG_BUILD_PATH = './_build/js/debug/build/moonscratch.js' |
| 9 | + |
| 10 | +const toAbsolutePath = ( |
| 11 | + importer: string | null | undefined, |
| 12 | + importPath: string, |
| 13 | +) => { |
| 14 | + const baseDir = importer ? dirname(importer) : process.cwd() |
| 15 | + const normalizedCandidate = importPath.replace(/^\.\.\/\.\.\//, './') |
| 16 | + const candidates = [ |
| 17 | + resolve(baseDir, importPath), |
| 18 | + resolve(process.cwd(), importPath), |
| 19 | + resolve(process.cwd(), normalizedCandidate), |
| 20 | + ] |
| 21 | + for (const candidate of candidates) { |
| 22 | + if (existsSync(candidate)) { |
| 23 | + return candidate |
| 24 | + } |
| 25 | + } |
| 26 | + return undefined |
| 27 | +} |
| 28 | + |
| 29 | +const resolveBindingPath = (importer: string | null | undefined) => { |
| 30 | + const releasePath = toAbsolutePath(importer, RELEASE_IMPORTER_PATH) |
| 31 | + if (releasePath) { |
| 32 | + return releasePath |
| 33 | + } |
| 34 | + if (existsSync(resolve(process.cwd(), DEBUG_BUILD_PATH))) { |
| 35 | + return resolve(process.cwd(), DEBUG_BUILD_PATH) |
| 36 | + } |
| 37 | + const debugPath = toAbsolutePath(importer, DEBUG_BINDING_PATH) |
| 38 | + return debugPath |
| 39 | +} |
| 40 | + |
3 | 41 | export default defineConfig({ |
4 | 42 | pack: { |
5 | 43 | entry: 'js/index.ts', |
6 | 44 | dts: true, |
| 45 | + plugins: [ |
| 46 | + { |
| 47 | + name: 'mbt-binding', |
| 48 | + resolveId(id, importer) { |
| 49 | + if (id === RELEASE_BINDING_PATH) { |
| 50 | + return resolveBindingPath(importer) |
| 51 | + } |
| 52 | + }, |
| 53 | + }, |
| 54 | + ], |
7 | 55 | }, |
8 | 56 | test: { |
9 | 57 | include: ['./js/**/*.test.ts'], |
|
0 commit comments