Skip to content

Commit

Permalink
feat: pass isBuild, path & query to transform functions
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed May 19, 2020
1 parent 5b75f56 commit ce4032b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/node/build/buildPluginCss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const createBuildCssPlugin = (
const { path, query } = parseWithQuery(id)
for (const t of transforms) {
if (t.test(path, query)) {
css = await t.transform(css, true)
css = await t.transform(css, true, true, path, query)
transformed = true
break
}
Expand Down
1 change: 1 addition & 0 deletions src/node/build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export async function createBaseRollupPlugins(
const { rollupInputOptions = {}, transforms = [] } = options

// TODO allow user to configure known named exports
// or upgrade @rollup/plugin-commonjs when the new version is out
const knownNamedExports: Record<string, string[]> = {}
for (const id of PACKAGES_TO_AUTO_DETECT_EXPORTS) {
knownNamedExports[id] =
Expand Down
27 changes: 21 additions & 6 deletions src/node/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,25 @@ import { ServerPlugin } from './server'
import { Plugin as RollupPlugin } from 'rollup'
import { parseWithQuery, readBody, isImportRequest } from './utils'

type ParsedQuery = Record<string, string | string[] | undefined>

export interface Transform {
/**
* @default 'js'
*/
as?: 'js' | 'css'
test: (
test: (path: string, query: ParsedQuery) => boolean
transform: (
code: string,
/**
* Indicates whether this is a request made by js import(), or natively by
* the browser (e.g. `<img src="...">`).
*/
isImport: boolean,
isBuild: boolean,
path: string,
query: Record<string, string | string[] | undefined>
) => boolean
transform: (code: string, isImport: boolean) => string | Promise<string>
query: ParsedQuery
) => string | Promise<string>
}

export function createServerTransformPlugin(
Expand All @@ -26,7 +35,13 @@ export function createServerTransformPlugin(
if (ctx.body) {
const code = await readBody(ctx.body)
if (code) {
ctx.body = await t.transform(code, isImportRequest(ctx))
ctx.body = await t.transform(
code,
isImportRequest(ctx),
false,
ctx.path,
ctx.query
)
ctx._transformed = true
}
}
Expand All @@ -48,7 +63,7 @@ export function createBuildJsTransformPlugin(
let result: string | Promise<string> = code
for (const t of transforms) {
if (t.test(path, query)) {
result = await t.transform(result, true)
result = await t.transform(result, true, true, path, query)
}
}
return result
Expand Down

0 comments on commit ce4032b

Please sign in to comment.