rollup#PluginContext TypeScript Examples
The following examples show how to use
rollup#PluginContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: resolver.ts From vite-tsconfig-paths with MIT License | 6 votes |
export function getResolver(opts?: PluginOptions) {
const plugin = tsPaths(opts)
const container: Partial<PluginContext> = {
async resolve(id, importer) {
const resolved = viteResolve(id, importer)
return resolved && ({ id: resolved } as any)
},
}
plugin.configResolved!({ root: __dirname } as any)
Object.assign(plugin, container)
const resolveId = plugin.resolveId!.bind(plugin as any) as (
id: string,
importer?: string
) => Promise<string | undefined>
return async (id: string, importer?: string) => {
const expectsPosix = importer?.[0] == '/'
if (isWindows && expectsPosix) {
importer = resolve(importer!)
}
const resolved = await resolveId(id, importer)
if (resolved) {
// Strip the D: prefix on Windows if the importer was a Posix-style path.
return isWindows && expectsPosix ? resolved.slice(2) : resolved
}
}
}
Example #2
Source File: plugins.test.ts From backstage with Apache License 2.0 | 5 votes |
context = {
meta: {
rollupVersion: '0.0.0',
watchMode: false,
},
} as PluginContext
Example #3
Source File: createRollupPluginContexts.ts From web with MIT License | 5 votes |
/**
* Runs rollup with an empty module in order to capture the plugin context and
* normalized options.
* @param inputOptions
*/
export async function createRollupPluginContexts(
inputOptions: InputOptions,
): Promise<RollupPluginContexts> {
let normalizedInputOptions: NormalizedInputOptions | undefined = undefined;
let pluginContext: PluginContext | undefined = undefined;
let transformPluginContext: TransformPluginContext | undefined = undefined;
await rollup({
...inputOptions,
input: 'noop',
plugins: [
{
name: 'noop',
buildStart(options) {
normalizedInputOptions = options;
},
resolveId(id) {
pluginContext = this;
return id;
},
load() {
return '';
},
transform() {
transformPluginContext = this;
return null;
},
},
],
});
if (!normalizedInputOptions || !pluginContext || !transformPluginContext) {
throw new TypeError();
}
return {
normalizedInputOptions,
pluginContext,
transformPluginContext,
minimalPluginContext: { meta: (pluginContext as PluginContext).meta },
};
}
Example #4
Source File: emitAssets.ts From web with MIT License | 5 votes |
export async function emitAssets(
this: PluginContext,
inputs: InputData[],
options: RollupPluginHTMLOptions,
) {
const emittedStaticAssets = new Map<string, string>();
const emittedHashedAssets = new Map<string, string>();
const emittedStaticAssetNames = new Set();
const transforms: TransformAssetFunction[] = [];
if (options.transformAsset) {
if (Array.isArray(options.transformAsset)) {
transforms.push(...options.transformAsset);
} else {
transforms.push(options.transformAsset);
}
}
const staticAssets: InputAsset[] = [];
const hashedAssets: InputAsset[] = [];
for (const input of inputs) {
for (const asset of input.assets) {
if (asset.hashed) {
hashedAssets.push(asset);
} else {
staticAssets.push(asset);
}
}
}
// ensure static assets are last because of https://github.com/rollup/rollup/issues/3853
const allAssets = [...hashedAssets, ...staticAssets];
for (const asset of allAssets) {
const map = asset.hashed ? emittedHashedAssets : emittedStaticAssets;
if (!map.has(asset.filePath)) {
let source: Buffer = asset.content;
// run user's transform functions
for (const transform of transforms) {
const result = await transform(asset.content, asset.filePath);
if (result != null) {
source = typeof result === 'string' ? Buffer.from(result, 'utf-8') : result;
}
}
let ref: string;
let basename = path.basename(asset.filePath);
if (asset.hashed) {
ref = this.emitFile({ type: 'asset', name: basename, source });
} else {
// ensure the output filename is unique
let i = 1;
while (emittedStaticAssetNames.has(basename)) {
const ext = path.extname(basename);
basename = `${basename.replace(ext, '')}${i}${ext}`;
i += 1;
}
emittedStaticAssetNames.add(basename);
const fileName = `assets/${basename}`;
ref = this.emitFile({ type: 'asset', name: basename, fileName, source });
}
map.set(asset.filePath, this.getFileName(ref));
}
}
return { static: emittedStaticAssets, hashed: emittedHashedAssets };
}
Example #5
Source File: createRollupPluginContextAdapter.ts From web with MIT License | 4 votes |
export function createRollupPluginContextAdapter<
T extends PluginContext | MinimalPluginContext | TransformPluginContext,
>(
pluginContext: T,
wdsPlugin: WdsPlugin,
config: DevServerCoreConfig,
fileWatcher: FSWatcher,
context: Context,
pluginMetaPerModule: Map<string, CustomPluginOptions>,
) {
return {
...pluginContext,
getModuleInfo(id: string): ModuleInfo {
return {
id,
code: context.body as string,
ast: null,
dynamicallyImportedIds: [],
dynamicallyImportedIdResolutions: [],
dynamicImporters: [],
hasDefaultExport: false,
implicitlyLoadedBefore: [],
implicitlyLoadedAfterOneOf: [],
importedIds: [],
importedIdResolutions: [],
importers: [],
isEntry: false,
isExternal: false,
isIncluded: false,
hasModuleSideEffects: false,
syntheticNamedExports: false,
meta: pluginMetaPerModule.get(id) ?? {},
};
},
addWatchFile(id: string) {
const filePath = path.join(process.cwd(), id);
fileWatcher.add(filePath);
},
emitAsset() {
throw new Error('Emitting files is not yet supported');
},
emitFile() {
throw new Error('Emitting files is not yet supported');
},
getAssetFileName() {
throw new Error('Emitting files is not yet supported');
},
getFileName() {
throw new Error('Emitting files is not yet supported');
},
setAssetSource() {
throw new Error('Emitting files is not yet supported');
},
async resolve(source: string, importer: string, options: { skipSelf: boolean }) {
if (!context) throw new Error('Context is required.');
for (const pl of config.plugins ?? []) {
if (
pl.resolveImport &&
(!options.skipSelf || pl.resolveImport !== wdsPlugin.resolveImport)
) {
const result = await pl.resolveImport({ source, context });
let resolvedId: string | undefined;
if (typeof result === 'string') {
resolvedId = result;
} else if (typeof result === 'object') {
resolvedId = result?.id;
}
if (resolvedId) {
const importerDir = path.dirname(importer);
return {
id: path.isAbsolute(resolvedId) ? resolvedId : path.join(importerDir, resolvedId),
};
}
}
}
},
async resolveId(source: string, importer: string, options: { skipSelf: boolean }) {
const resolveResult = await this.resolve(source, importer, options);
if (typeof resolveResult === 'string') {
return resolveResult;
}
if (typeof resolveResult === 'object') {
return resolveResult?.id;
}
return resolveResult;
},
};
}