Skip to content

Commit

Permalink
feat: generate sourcemap #28
Browse files Browse the repository at this point in the history
  • Loading branch information
yejimeiming committed Jul 12, 2023
1 parent 4257aa6 commit dfd8742
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/index.ts
@@ -1,15 +1,17 @@
import fs from 'node:fs'
import path from 'node:path'
import type { Plugin, ResolvedConfig } from 'vite'
import type { SourceMapInput } from 'rollup'
import type { Loader } from 'esbuild'
import { parse as parseAst } from 'acorn'
import MagicString from 'magic-string'
import {
DEFAULT_EXTENSIONS,
KNOWN_SFC_EXTENSIONS,
KNOWN_ASSET_TYPES,
KNOWN_CSS_TYPES,
} from 'vite-plugin-utils/constant'
import { MagicString, cleanUrl } from 'vite-plugin-utils/function'
import { cleanUrl } from 'vite-plugin-utils/function'
import { analyzer } from './analyze'
import { generateImport } from './generate-import'
import { generateExport } from './generate-export'
Expand Down Expand Up @@ -77,17 +79,17 @@ export default function commonjs(options: Options = {}): Plugin {
return
}

const contents = await transformCommonjs({
const result = await transformCommonjs({
options,
code,
id,
extensions,
dynaimcRequire,
})

if (contents != null) {
if (result != null) {
return {
contents,
contents: result.code,
loader: id.slice(id.lastIndexOf('.') + 1) as Loader,
}
}
Expand Down Expand Up @@ -119,7 +121,7 @@ async function transformCommonjs({
id: string,
extensions: string[],
dynaimcRequire: DynaimcRequire,
}) {
}): Promise<{ code: string; map: SourceMapInput; } | null | undefined> {
if (!(extensions.includes(path.extname(id)) || extensions.includes(path.extname(cleanUrl(id))))) return
if (!isCommonjs(code)) return

Expand Down Expand Up @@ -218,6 +220,10 @@ async function transformCommonjs({
}
}

const str = ms.toString()
return str !== code ? str : null
if (ms.hasChanged()) {
return {
code: ms.toString(),
map: ms.generateMap({ hires: true, source: id }),
}
}
}

0 comments on commit dfd8742

Please sign in to comment.