feat: support rewriting urls
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
Miel Truyen 2023-06-13 02:02:41 +02:00
parent 48dcdefee1
commit 6e50208557
8 changed files with 99 additions and 7 deletions

View File

@ -64,7 +64,7 @@ Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#comma
### `template` ### `template`
Type: `Function`<br> Type: `Function`\
Default: `undefined`\ Default: `undefined`\
Returns: `String` Returns: `String`
@ -94,9 +94,6 @@ async function build() {
By default, this plugin supports the `esm` (`es`). Any other format is currently untested as this plugin is in an early state, see [#status](#status) By default, this plugin supports the `esm` (`es`). Any other format is currently untested as this plugin is in an early state, see [#status](#status)
## Status ## Status
This plugin is in an early state. As such not everything that is supported yet, the options are laregely undocumented and may change.
### (Rudimentarily) supported ### (Rudimentarily) supported
- Importing JS via `<script src="..." type="module">` tags - Importing JS via `<script src="..." type="module">` tags
- Importing assets using @rollup/plugin-url (which could use an update TBH) - Importing assets using @rollup/plugin-url (which could use an update TBH)

View File

@ -1,6 +1,6 @@
{ {
"name": "rollup-plugin-html-entry2", "name": "rollup-plugin-html-entry2",
"version": "0.0.5", "version": "0.0.6",
"description": "Teaches rollup how to deal with HTML, allows to use HTML-files as entry-points.", "description": "Teaches rollup how to deal with HTML, allows to use HTML-files as entry-points.",
"license": "MIT", "license": "MIT",
"repository": { "repository": {

View File

@ -1,4 +1,4 @@
import { extname } from "node:path"; import path, { extname } from "node:path";
import type { import type {
Plugin, Plugin,
@ -48,6 +48,7 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
const { const {
publicPath, publicPath,
transform, transform,
rewriteUrl,
load, load,
htmlFileNames, htmlFileNames,
resolve, resolve,
@ -353,7 +354,12 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
htmlContents = htmlContents.replace(htmlImport.placeholder, importResult.code); htmlContents = htmlContents.replace(htmlImport.placeholder, importResult.code);
}else if(htmlImport.type === 'entryChunk'){ }else if(htmlImport.type === 'entryChunk'){
const relPath = posix.relative(dirname(chunk.fileName), importResult.fileName); const relPath = posix.relative(dirname(chunk.fileName), importResult.fileName);
htmlContents = htmlContents.replace(htmlImport.placeholder, relPath); const rootPath = path.posix.join(dirname(chunk.fileName), relPath);
const rewritten = rewriteUrl? await Promise.resolve(rewriteUrl(relPath, {
from: chunk.fileName,
rootPath,
})): relPath;
htmlContents = htmlContents.replace(htmlImport.placeholder, rewritten);
} }
} }
} }

View File

@ -0,0 +1,5 @@
export const bootstrap = (el,deps = [])=>{
el.innerHtml = `
<div>load the app</div>
`;
}

View File

@ -0,0 +1,8 @@
<html>
<head>
</head>
<body>
<div id="root"></div>
<script src="./app.js" type="module"></script>
</body>
</html>

View File

@ -0,0 +1,8 @@
<html>
<head>
</head>
<body>
<div id="root"></div>
<script src="./admin/app.js" type="module"></script>
</body>
</html>

44
test/rewrite-url/test.js Normal file
View File

@ -0,0 +1,44 @@
import {resolve, join, dirname} from "node:path";
import * as path from "node:path";
import test from "ava";
import { rollup } from "rollup";
import {debugPrintOutput, getCode} from "../util/test.js";
import html from "../../src/index.ts";
const output = {
dir: 'output', // Output all files
format: 'es', // iifi and cjs should be added to tests
sourcemap: true,// Test if #sourcemapUrl is not accidentally included in the html-output
};
import {fileURLToPath} from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
process.chdir(join(__dirname, 'fixtures'));
test.serial('rewrite-url', async (t) => {
const bundle = await rollup({
input: {
['index']: 'index.html',
['admin/index']: resolve(__dirname,'fixtures','admin/index.html'),
['admin/app']: resolve(__dirname,'fixtures','admin/app.js'),
},
plugins: [
html({
rewriteUrl(relative, {rootPath, from}){
return `/${rootPath}`;
}
}),
]
});
const code = await getCode(bundle, output, true);
debugPrintOutput('rewrite-url',code);
t.snapshot(code);
});
// TODO various parameters
// - format: cjs, iifi, ...
// - sourcemap: inline, false, (and the various exotic sourcemap options)
// Watch mode tests would be its own dir
// ...

24
types/index.d.ts vendored
View File

@ -15,6 +15,11 @@ export interface RollupHtmlTransformContext {
// files: Record<string, (OutputChunk | OutputAsset)[]>; // files: Record<string, (OutputChunk | OutputAsset)[]>;
} }
export interface RewriteUrlCallbackContext {
from: string;
rootPath: string;
}
export type RewriteUrlCallback = (relative: string, context: RewriteUrlCallbackContext) => string|Promise<string>;
export type TransformCallback = (source: string, transformContext: RollupHtmlTransformContext) => string|Promise<string>; export type TransformCallback = (source: string, transformContext: RollupHtmlTransformContext) => string|Promise<string>;
export interface RollupHtmlOptions { export interface RollupHtmlOptions {
@ -23,6 +28,7 @@ export interface RollupHtmlOptions {
* Follows the same logic as rollup's [entryFileNames](https://rollupjs.org/configuration-options/#output-entryfilenames). * Follows the same logic as rollup's [entryFileNames](https://rollupjs.org/configuration-options/#output-entryfilenames).
*/ */
htmlFileNames?: string|((chunkInfo: PreRenderedChunk) => string); htmlFileNames?: string|((chunkInfo: PreRenderedChunk) => string);
/** /**
* Transform a source file passed into this plugin to HTML. For example: a handlebars transform * Transform a source file passed into this plugin to HTML. For example: a handlebars transform
* ``` * ```
@ -33,6 +39,17 @@ export interface RollupHtmlOptions {
*/ */
transform?: TransformCallback; transform?: TransformCallback;
/**
* Optional callback to rewrite how resources are referenced in the output HTML.
* For example to rewrite urls to as paths from the root of your website:
* ```
* rewriteUrl(relative, {rootPath, from}){
* return `/${rootPath}`;
* }
* ```
*/
rewriteUrl?: RewriteUrlCallback;
/** /**
* Detect which references (<a href="...">, <img src="...">) to resolve from a HTML node. * Detect which references (<a href="...">, <img src="...">) to resolve from a HTML node.
* This rarely needs to be overloaded, but can be used to support non-native attributes used by custom-elements. * This rarely needs to be overloaded, but can be used to support non-native attributes used by custom-elements.
@ -49,7 +66,14 @@ export interface RollupHtmlOptions {
* Return a falsey value to skip this reference. Return true to resolve as is. (or string to transform the id) * Return a falsey value to skip this reference. Return true to resolve as is. (or string to transform the id)
*/ */
resolve?: ResolveCallback; resolve?: ResolveCallback;
/**
* [Pattern](https://github.com/micromatch/picomatch#globbing-features) to include
*/
include?: FilterPattern; include?: FilterPattern;
/**
* [Pattern](https://github.com/micromatch/picomatch#globbing-features) to exclude
*/
exclude?: FilterPattern exclude?: FilterPattern
} }