Skip to content

Commit

Permalink
refactor: remove using resolvePackageData from Vite (#1153)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Oct 23, 2023
1 parent 023e1ae commit 0de98b8
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 13 deletions.
25 changes: 12 additions & 13 deletions packages/slidev/node/plugins/monacoTransform.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
import { join } from 'node:path'
import { dirname, join } from 'node:path'
import fs from 'node:fs/promises'
import process from 'node:process'
import { slash } from '@antfu/utils'
import type { Plugin } from 'vite'
import { findDepPkgJsonPath } from 'vitefu'

async function getPackageData(pkg: string) {
// Trick the bundler to avoid transforming dynamic import to require.
// The "resolvePackageData" is not available in CommonJS build of Vite.
// eslint-disable-next-line no-eval
const { resolvePackageData } = await eval('import("vite")')

const info = resolvePackageData(pkg, process.cwd())
if (!info)
const pkgJsonPath = await findDepPkgJsonPath(pkg, process.cwd())
if (!pkgJsonPath)
return

const typePath = info.data.types || info.data.typings
const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, 'utf-8'))

const typePath = pkgJson.types || pkgJson.typings
if (!typePath)
return

return [info, typePath]
return [dirname(pkgJsonPath), pkgJson, typePath]
}

export function createMonacoTypesLoader(): Plugin {
Expand All @@ -38,12 +37,12 @@ export function createMonacoTypesLoader(): Plugin {
if (!packageData)
return

const [info, typePath] = packageData
const [pkgDir, pkgJson, typePath] = packageData

return [
'import * as monaco from \'monaco-editor\'',
`import Type from "${slash(join(info.dir, typePath))}?raw"`,
...Object.keys(info.data.dependencies || {}).map(i => `import "/@slidev-monaco-types/${i}"`),
`import Type from "${slash(join(pkgDir, typePath))}?raw"`,
...Object.keys(pkgJson.dependencies || {}).map(i => `import "/@slidev-monaco-types/${i}"`),
`monaco.languages.typescript.typescriptDefaults.addExtraLib(\`declare module "${pkg}" { \$\{Type\} }\`)`,
].join('\n')
}
Expand Down
1 change: 1 addition & 0 deletions packages/slidev/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"vite-plugin-static-copy": "^0.17.0",
"vite-plugin-vue-server-ref": "^0.3.4",
"vite-plugin-windicss": "^1.9.1",
"vitefu": "^0.2.5",
"vue": "^3.3.4",
"windicss": "^3.5.6",
"yargs": "^17.7.2"
Expand Down
14 changes: 14 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 0de98b8

Please sign in to comment.