Skip to content

Commit

Permalink
feat: resolveId supports Rollup externals (#18)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
tropicalraisel and antfu committed Sep 11, 2021
1 parent 73f550a commit 3c756dd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
4 changes: 3 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@ export type Thenable<T> = T | Promise<T>

export type TransformResult = string | { code: string; map?: SourceMap | null; } | null | undefined

export type ExternalIdResult = { id: string, external?: boolean }

export interface UnpluginOptions {
name: string;
enforce?: 'post' | 'pre' | undefined;
buildStart?: () => Promise<void> | void;
transformInclude?: (id: string) => boolean;
transform?: (this: UnpluginContext, code: string, id: string) => Thenable<TransformResult>;
load?: (this: UnpluginContext, id: string) => Thenable<TransformResult>
resolveId?: (id: string, importer?: string) => Thenable<string | null | undefined>
resolveId?: (id: string, importer?: string) => Thenable<string | ExternalIdResult | null | undefined>

// framework specify extends
rollup?: Partial<RollupPlugin>
Expand Down
12 changes: 8 additions & 4 deletions src/webpack/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs'
import { fileURLToPath } from 'url'
import path from 'upath'
import VirtualModulesPlugin from 'webpack-virtual-modules'
import type { Resolver } from 'enhanced-resolve'
import type { Resolver, ResolveRequest } from 'enhanced-resolve'
import type { UnpluginContextMeta, UnpluginInstance, UnpluginFactory, WebpackCompiler, ResolvedUnpluginOptions } from '../types'

const _dirname = typeof __dirname !== 'undefined' ? __dirname : path.dirname(fileURLToPath(import.meta.url))
Expand Down Expand Up @@ -78,17 +78,21 @@ export function getWebpackPlugin<UserOptions = {}> (
const resolver = {
apply (resolver: Resolver) {
const target = resolver.ensureHook('resolve')
const tap = () => async (request: any, resolveContext: any, callback: any) => {
const tap = () => async (request: ResolveRequest, resolveContext: any, callback: any) => {
// filter out invalid requests
if (!request.request || request.request.startsWith(plugin.__virtualModulePrefix)) {
return callback()
}

// call hook
let resolved = await plugin.resolveId!(request.request)
if (resolved == null) {
const result = await plugin.resolveId!(request.request)
if (result == null) {
return callback()
}
let resolved = typeof result === 'string' ? result : result.id

// TODO: support external
// const isExternal = typeof result === 'string' ? false : result.external === true

// if the resolved module is not exists,
// we treat it as a virtual module
Expand Down

0 comments on commit 3c756dd

Please sign in to comment.