9 Commits

Author SHA1 Message Date
5d2a45ef81 fix: missing test snapshots
All checks were successful
continuous-integration/drone/push Build is passing
2023-06-13 02:03:26 +02:00
6e50208557 feat: support rewriting urls
Some checks failed
continuous-integration/drone/push Build is failing
2023-06-13 02:02:41 +02:00
48dcdefee1 0.0.5: fix, try to resolve sensible entrynames even if files were imported with an absolute path
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-20 23:39:14 +02:00
ba09aaf915 0.0.4: increment version number for fix: fix entryNames of sources files included by html in a subdir (they didnt keep their relative address...)
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-20 23:17:02 +02:00
9bf026f0c3 0.0.3: fix entryNames of sources files included by html in a subdir (they didnt keep their relative address...)
Some checks failed
continuous-integration/drone/push Build is failing
2023-05-20 23:14:59 +02:00
a784abc1b0 Build-fix: update snapshotting code to generate a predictable (A-Z) ordering of the snapshotted files
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-20 21:57:36 +02:00
52c104f781 0.0.3: Fixed a bug that showed up in watch mode
Some checks failed
continuous-integration/drone/push Build is failing
2023-05-20 21:05:37 +02:00
b18ac5c361 0.0.2: Package increment
All checks were successful
continuous-integration/drone/push Build is passing
2023-05-02 16:16:40 +02:00
ba07649981 0.0.2: Updated docs to reflect current state
Some checks failed
continuous-integration/drone/push Build is failing
2023-05-02 15:47:23 +02:00
26 changed files with 490 additions and 56 deletions

View File

@@ -1,2 +1,28 @@
# 0.0.2
Private release update. Added experimental support for:
- multiple-entrypoints (i.e index.html and admin/index.html)
- Inlined scripts (i.e <script type="module">...</script>)
# 0.0.1
Initial private release
# Open issues / Short-term ToDo's:
- Implement importing style (#1 linking to a pcss, #2 inlined style)
- Importing html as a JSModule
- Testing on a windows machine and fix whatever issues with paths that come out of it
- Code clean-up / Watch-mode support
- Properly use 'meta' property, and supporting caching
- Supporting 'assets' directly (LoadType) using emitFile({type:'asset',...}). Removes the need for @rollup/plugin-url in small projects (altough it is still the preferred way of including assets)
- Getting rid of the module evaluation step if possible
- Clean up our API, keeping in mind the configurability desired:
- resolving language for inline script/style
- excluding non-relative imports (ie unpkg stuff etc)
- customizing how to import certain things (LoadType)
- support for typescript (might not need extra work, but it should be integrated in tests)
- cjs & iifi supported in tests

View File

@@ -64,7 +64,7 @@ Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#comma
### `template`
Type: `Function`<br>
Type: `Function`\
Default: `undefined`\
Returns: `String`
@@ -94,27 +94,28 @@ 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)
## Status
This plugin is in an early state. As such not everything that is supported yet, and the options may change.
### (Rudimentarily) supported
- Importing JS via `<script src="..." type="module">` tags
- Importing assets using @rollup/plugin-url (which could use an update TBH)
- Compatibility with other plugins such as @rollup/plugin-node-resolve, @rollup/plugin-babel, @rollup/plugin-commonjs, @rollup/plugin-terser and rollup-plugin-livereload
### Not (yet) supported
- Inline scripts (i.e `<script>...</script>`)
### Not (yet/properly) supported
- Sourcemaps (inlined script) (dev-note: we're already including magic-string for this, but do not use it yet, neeeds refactoring)
- Plugins importing CSS files
- CommonJS (cjs) and IIFI output formats. (Is UMD actually ever used?)
- Overriding which tags to ignore/include
- Other (various) plugins such as those for HMR etc
- Overriding which DOM-nodes and resulting URLS to ignore/include (in a clean way)
- Other (various) plugins such as typescript, or those for HMR etc
- ...
# Contibuting
You can be helpful by testing, proving helpful feedback, expanding the documentation, responding to issues/questions being reported, resolving the many ToDo`s in the code, implementating features...\
[Get in touch](mailto:rollup-plugin-html-entry2@cerxes.net) or just dive into [the code](https://git.cerxes.net/rollup-apps/plugin-html) or [issues](https://git.cerxes.net/rollup-apps/plugin-html/issues)
[Get in touch](mailto:rollup-plugin-html-entry2@cerxes.net) or just dive into [the code](https://git.cerxes.net/rollup-apps/plugin-html) or [issues](https://git.cerxes.net/rollup-apps/plugin-html/issues).
See also the ToDo-list at the end of the [changelog](./CHANGELOG.md)
# Notes
## git.cerxes.net

View File

@@ -1,6 +1,6 @@
{
"name": "rollup-plugin-html-entry2",
"version": "0.0.1",
"version": "0.0.6",
"description": "Teaches rollup how to deal with HTML, allows to use HTML-files as entry-points.",
"license": "MIT",
"repository": {
@@ -56,7 +56,8 @@
},
"dependencies": {
"@rollup/pluginutils": "^5.0.1",
"parse5": "^7.1.2"
"parse5": "^7.1.2",
"magic-string": "^0.30.0"
},
"devDependencies": {
"@types/node": "^18.15.11",

11
pnpm-lock.yaml generated
View File

@@ -4,6 +4,9 @@ dependencies:
'@rollup/pluginutils':
specifier: ^5.0.1
version: 5.0.2(rollup@3.20.3)
magic-string:
specifier: ^0.30.0
version: 0.30.0
parse5:
specifier: ^7.1.2
version: 7.1.2
@@ -475,7 +478,6 @@ packages:
/@jridgewell/sourcemap-codec@1.4.15:
resolution: {integrity: sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==}
dev: true
/@jridgewell/trace-mapping@0.3.18:
resolution: {integrity: sha512-w+niJYzMHdd7USdiH2U6869nqhD2nbfZXND5Yp93qIbEmnDNk7PD48o+YchRVpzMU7M6jVCbenTR7PA1FLQ9pA==}
@@ -2139,6 +2141,13 @@ packages:
yallist: 4.0.0
dev: true
/magic-string@0.30.0:
resolution: {integrity: sha512-LA+31JYDJLs82r2ScLrlz1GjSgu66ZV518eyWT+S8VhyQn/JL0u9MeBOvQMGYiPk1DBiSN9DDMOcXvigJZaViQ==}
engines: {node: '>=12'}
dependencies:
'@jridgewell/sourcemap-codec': 1.4.15
dev: false
/make-dir@3.1.0:
resolution: {integrity: sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==}
engines: {node: '>=8'}

View File

@@ -1,4 +1,4 @@
import { extname } from "node:path";
import path, { extname } from "node:path";
import type {
Plugin,
@@ -48,6 +48,7 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
const {
publicPath,
transform,
rewriteUrl,
load,
htmlFileNames,
resolve,
@@ -61,13 +62,22 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
if(publicPath){ throw new Error("TODO, do something with the public path or throw it out of the options. this is just to stop typescript complaining")}
let filter = createFilter(include, exclude, {});
// TODO, we need to clear all these properly at sme point to avoid odd bugs in watch mode
let htmlModules = new Map<string, HtmlModule>();// todo clean this per new build?
let virtualSources = new Map<string, string>();
let addedEntries = new Map<string, string>();
let entryNames = new Map<string,string>();
const pluginName = 'html2';
return {
name: pluginName,// TODO: Need a better name, original plugin was just named `html` and might still make sense to use in conjunction with this one
buildStart(options){
entryNames = new Map(Object.entries(typeof(options.input)==='object'?options.input:{[options.input]:[options.input]})
.map(([k,v])=>[v,k])
);
},
resolveId: {
async handler(specifier: string,
importer: string | undefined,
@@ -106,7 +116,8 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
}
}
},
load: {
load: { // TODO, not in the mood to fix this. Load-result is getting cached and that gives us issues. Seperate load/transform behavior and adapt to use magic string for transformations?
// Something to figure out: its counter intuitive that rollup expects the load-callback to already return JS. It implies we already do transformations and can't really use rollup to further transform any of it. (i.e handlebars > intermediate-html > html would not be possible?)
async handler(id: string) {
if(virtualSources.has(id)) return virtualSources.get(id);
if(!filter(id)) return;
@@ -121,7 +132,7 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
}) : contents;
// Parse document and store it (TODO: check for watch mode, we should check if it needs reparsing or not)
const document = htmlModule.document = htmlModule.document ?? parseHtml(htmlSrc);
const document = htmlModule.document = parseHtml(htmlSrc);
// Figure out which references to load from this HTML by iterating all nodes (looking for src or href attributes)
let htmlImports: HtmlImport[] = htmlModule.imports = [];
@@ -142,7 +153,6 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
if(source){
virtualSources.set(sourceId, source);
}
const resolved = await this.resolve(sourceId, id, {
isEntry: type==='entryChunk',
});
@@ -151,7 +161,17 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
}
const selfInfo = this.getModuleInfo(id);
const importName = (source && selfInfo?.meta[pluginName].name) ? makeInlineId(selfInfo?.meta[pluginName].name, node, extname(sourceId)) : undefined;
let entryName: string|undefined = undefined;
const parentName = entryNames.get(id)??selfInfo?.meta[pluginName].name;
if(type==='entryChunk'){
entryName= posix.join(posix.dirname(parentName),sourceId);
entryName = entryName.slice(0,-(posix.extname(entryName).length)); // Cut off the extension (TODO, is this wise?)
}
const importName = (source && selfInfo?.meta[pluginName].name)
? makeInlineId(parentName, node, extname(sourceId))
: entryName;
const htmlImport: HtmlImport = {
id: <string>sourceId,
@@ -170,6 +190,9 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
placeholder: `html-import-${crypto.randomBytes(32).toString('base64')}`,
index: htmlImports.length,
}
// if(entryName){
// addedEntries.set(resolved.id, entryName);// (we could do this using meta?)
// }
htmlImports.push(htmlImport);
return htmlImport.placeholder;
}
@@ -223,12 +246,15 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
...options,
entryFileNames: (chunkInfo)=>{
const htmlModule = chunkInfo.facadeModuleId ? htmlModules.get(chunkInfo.facadeModuleId!) : null;
const addedEntry = chunkInfo.facadeModuleId ? addedEntries.get(chunkInfo.facadeModuleId!) : null;
const defaultOption = options.entryFileNames ?? "[name]-[hash].js";// This default is copied from the docs. TODO: don't like overwrite it this way, can we remove the need for this or fetch the true default?
if(htmlModule){
let fileName = typeof (htmlFileNames) === 'string' ? htmlFileNames : (<(chunkInfo:PreRenderedChunk)=>string>htmlFileNames)(chunkInfo);
if(fileName) {
return fileName;
}
}else if(addedEntry){
return addedEntry;
}
return typeof (defaultOption) === 'string' ? defaultOption : (<(chunkInfo:PreRenderedChunk)=>string>defaultOption)(chunkInfo);
},
@@ -328,7 +354,12 @@ export default function html(opts: RollupHtmlOptions = {}): Plugin {
htmlContents = htmlContents.replace(htmlImport.placeholder, importResult.code);
}else if(htmlImport.type === 'entryChunk'){
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

@@ -49,6 +49,8 @@ export function makeInlineId(sourceId: string, node: DefaultTreeAdapterMap['chil
export function makeLoader(mappings: NodeMapping[] = defaultMapping){
const fn : LoadNodeCallback = async function ({node, sourceId}, load){
for(const mapping of mappings){
// Test the mapping for a match
if (mapping.tagName && mapping.tagName !== node.tagName) continue; // No match, skip
if (mapping.match){
if(typeof(mapping.match) === 'function'){
@@ -67,7 +69,10 @@ export function makeLoader(mappings: NodeMapping[] = defaultMapping){
}
}
}
// If we've gotten this far its a valid mapping. (either inline or a src/href attribute)
if((<AttributeReference>mapping).attr){
// Mapped on attribute, resolve its src or href (or whatever was returned)
const attr = node.attrs.find(attr=>attr.name === (<AttributeReference>mapping).attr);
if(!attr) continue ;// No match, skip
const placeholder = await load({
@@ -76,6 +81,7 @@ export function makeLoader(mappings: NodeMapping[] = defaultMapping){
});
attr.value = placeholder;
}else if((<BodyReference>mapping).body){
// Mapped as body, use the contents of the DOM element
const body = serializeHtml(node); // unlike what you' might expect, this doesn't serialize the <script>-tag itself, only its contents. Which is what we want.
if(!body) continue; // Empty body, skip
const placeholder = await load({

View File

@@ -58,12 +58,6 @@ Generated by [AVA](https://avajs.dev).
> Snapshot 1
[
{
code: undefined,
fileName: 'script.html.body.script.js-e3b82208.js.map',
map: undefined,
source: '{"version":3,"file":"script.html.body.script.js-e3b82208.js","sources":["../batman.js","../script.html.body.script.js"],"sourcesContent":["export const b = ()=>\'batman\';\\nconsole.log(b());\\n","\\n import {b} from \\"./batman.js\\";\\n document.body.appendChild(\\n document.createTextNode(`Inline script including ${b()}`)\\n );\\n "],"names":[],"mappings":"AAAO,MAAM,CAAC,GAAG,IAAI,QAAQ,CAAC;AAC9B,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;;ACCJ,QAAQ,CAAC,IAAI,CAAC,WAAW;AACrC,gBAAgB,QAAQ,CAAC,cAAc,CAAC,CAAC,wBAAwB,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;AACzE,aAAa"}',
},
{
code: undefined,
fileName: 'script.html',
@@ -83,4 +77,10 @@ Generated by [AVA](https://avajs.dev).
</body></html>`,
},
{
code: undefined,
fileName: 'script.html.body.script.js-e3b82208.js.map',
map: undefined,
source: '{"version":3,"file":"script.html.body.script.js-e3b82208.js","sources":["../batman.js","../script.html.body.script.js"],"sourcesContent":["export const b = ()=>\'batman\';\\nconsole.log(b());\\n","\\n import {b} from \\"./batman.js\\";\\n document.body.appendChild(\\n document.createTextNode(`Inline script including ${b()}`)\\n );\\n "],"names":[],"mappings":"AAAO,MAAM,CAAC,GAAG,IAAI,QAAQ,CAAC;AAC9B,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;;ACCJ,QAAQ,CAAC,IAAI,CAAC,WAAW;AACrC,gBAAgB,QAAQ,CAAC,cAAc,CAAC,CAAC,wBAAwB,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;AACzE,aAAa"}',
},
]

Binary file not shown.

View File

@@ -0,0 +1,2 @@
export const b = ()=>'batman';
console.log(b());

View File

@@ -8,5 +8,6 @@
import {adminDeps} from "../app/admin-deps.js";
bootstrap(document.getElementById('root'), adminDeps());
</script>
<script src="./batman.js" type="module"></script>
</body>
</html>

View File

@@ -9,6 +9,64 @@ Generated by [AVA](https://avajs.dev).
> Snapshot 1
[
{
code: `const b = ()=>'batman';␊
console.log(b());␊
export { b };␊
//# sourceMappingURL=batman-c7fa228c.js.map␊
`,
fileName: 'admin/batman-c7fa228c.js',
map: SourceMap {
file: 'batman-c7fa228c.js',
mappings: 'AAAY,MAAC,CAAC,GAAG,IAAI,SAAS;AAC9B,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;;;;',
names: [],
sources: [
'../../admin/batman.js',
],
sourcesContent: [
`export const b = ()=>'batman';␊
console.log(b());␊
`,
],
version: 3,
},
source: undefined,
},
{
code: undefined,
fileName: 'admin/batman-c7fa228c.js.map',
map: undefined,
source: '{"version":3,"file":"batman-c7fa228c.js","sources":["../../admin/batman.js"],"sourcesContent":["export const b = ()=>\'batman\';\\nconsole.log(b());\\n"],"names":[],"mappings":"AAAY,MAAC,CAAC,GAAG,IAAI,SAAS;AAC9B,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;;;;"}',
},
{
code: undefined,
fileName: 'admin/index.body.script0.js-15dfaff3.js.map',
map: undefined,
source: '{"version":3,"file":"index.body.script0.js-15dfaff3.js","sources":["../../app/admin-deps.js","../../admin/index.html.body.script0.js"],"sourcesContent":["export function adminDeps(){\\n return \\"robin!\\";\\n}\\n","\\n import {bootstrap} from \\"../app/app.js\\"\\n import {adminDeps} from \\"../app/admin-deps.js\\";\\n bootstrap(document.getElementById(\'root\'), adminDeps());\\n "],"names":[],"mappings":";;AAAO,SAAS,SAAS,EAAE;AAC3B,IAAI,OAAO,QAAQ,CAAC;AACpB;;ACCY,SAAS,CAAC,QAAQ,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC"}',
},
{
code: undefined,
fileName: 'admin/index.html',
map: undefined,
source: `<html><head>␊
</head>␊
<body>␊
<div id="root"></div>␊
<script type="module">import { b as bootstrap } from '../app-01141b67.js';␊
function adminDeps(){␊
return "robin!";␊
}␊
bootstrap(document.getElementById('root'), adminDeps());␊
//# sourceMappingURL=index.body.script0.js-15dfaff3.js.map␊
</script>␊
<script src="batman-c7fa228c.js" type="module"></script>␊
</body></html>`,
},
{
code: `const bootstrap = (el,deps = [])=>{␊
el.innerHtml = \`
@@ -41,18 +99,6 @@ Generated by [AVA](https://avajs.dev).
},
source: undefined,
},
{
code: undefined,
fileName: 'index.html.body.script.js-45303f0f.js.map',
map: undefined,
source: '{"version":3,"file":"index.html.body.script.js-45303f0f.js","sources":["../index.html.body.script.js"],"sourcesContent":["\\n import {bootstrap} from \\"./app/app.js\\"\\n bootstrap(document.getElementById(\'root\'), \\"<none>\\");\\n "],"names":[],"mappings":";;AAEY,SAAS,CAAC,QAAQ,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC"}',
},
{
code: undefined,
fileName: 'admin/index.html.body.script.js-15dfaff3.js.map',
map: undefined,
source: '{"version":3,"file":"index.html.body.script.js-15dfaff3.js","sources":["../../app/admin-deps.js","../../admin/index.html.body.script.js"],"sourcesContent":["export function adminDeps(){\\n return \\"robin!\\";\\n}\\n","\\n import {bootstrap} from \\"../app/app.js\\"\\n import {adminDeps} from \\"../app/admin-deps.js\\";\\n bootstrap(document.getElementById(\'root\'), adminDeps());\\n "],"names":[],"mappings":";;AAAO,SAAS,SAAS,EAAE;AAC3B,IAAI,OAAO,QAAQ,CAAC;AACpB;;ACCY,SAAS,CAAC,QAAQ,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC"}',
},
{
code: undefined,
fileName: 'app-01141b67.js.map',
@@ -78,23 +124,8 @@ Generated by [AVA](https://avajs.dev).
},
{
code: undefined,
fileName: 'admin/index.html',
fileName: 'index.html.body.script.js-45303f0f.js.map',
map: undefined,
source: `<html><head>␊
</head>␊
<body>␊
<div id="root"></div>␊
<script type="module">import { b as bootstrap } from '../app-01141b67.js';␊
function adminDeps(){␊
return "robin!";␊
}␊
bootstrap(document.getElementById('root'), adminDeps());␊
//# sourceMappingURL=index.html.body.script.js-15dfaff3.js.map␊
</script>␊
</body></html>`,
source: '{"version":3,"file":"index.html.body.script.js-45303f0f.js","sources":["../index.html.body.script.js"],"sourcesContent":["\\n import {bootstrap} from \\"./app/app.js\\"\\n bootstrap(document.getElementById(\'root\'), \\"<none>\\");\\n "],"names":[],"mappings":";;AAEY,SAAS,CAAC,QAAQ,CAAC,cAAc,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC"}',
},
]

View File

@@ -1,4 +1,4 @@
import {join, dirname} from "node:path";
import {resolve, join, dirname} from "node:path";
import test from "ava";
import { rollup } from "rollup";
@@ -21,7 +21,7 @@ test.serial('multi-entry', async (t) => {
const bundle = await rollup({
input: {
['index']: 'index.html',
['admin/index']: 'admin/index.html'
['admin/index']: resolve(__dirname,'fixtures','admin/index.html'),
},
plugins: [
html({

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>

View File

@@ -0,0 +1,74 @@
# Snapshot report for `test/rewrite-url/test.js`
The actual snapshot is saved in `test.js.snap`.
Generated by [AVA](https://avajs.dev).
## rewrite-url
> Snapshot 1
[
{
code: `const bootstrap = (el,deps = [])=>{␊
el.innerHtml = \`
<div>load the app</div>␊
\`;␊
};␊
export { bootstrap };␊
//# sourceMappingURL=app-88ed8fd6.js.map␊
`,
fileName: 'admin/app-88ed8fd6.js',
map: SourceMap {
file: 'app-88ed8fd6.js',
mappings: 'AAAY,MAAC,SAAS,GAAG,CAAC,EAAE,CAAC,IAAI,GAAG,EAAE,GAAG;AACzC,IAAI,EAAE,CAAC,SAAS,GAAG,CAAC;AACpB;AACA,IAAI,CAAC,CAAC;AACN;;;;',
names: [],
sources: [
'../../admin/app.js',
],
sourcesContent: [
`export const bootstrap = (el,deps = [])=>{␊
el.innerHtml = \`␊
<div>load the app</div>␊
\`;␊
}␊
`,
],
version: 3,
},
source: undefined,
},
{
code: undefined,
fileName: 'admin/app-88ed8fd6.js.map',
map: undefined,
source: '{"version":3,"file":"app-88ed8fd6.js","sources":["../../admin/app.js"],"sourcesContent":["export const bootstrap = (el,deps = [])=>{\\n el.innerHtml = `\\n <div>load the app</div>\\n `;\\n}\\n"],"names":[],"mappings":"AAAY,MAAC,SAAS,GAAG,CAAC,EAAE,CAAC,IAAI,GAAG,EAAE,GAAG;AACzC,IAAI,EAAE,CAAC,SAAS,GAAG,CAAC;AACpB;AACA,IAAI,CAAC,CAAC;AACN;;;;"}',
},
{
code: undefined,
fileName: 'admin/index.html',
map: undefined,
source: `<html><head>␊
</head>␊
<body>␊
<div id="root"></div>␊
<script src="/admin/app-88ed8fd6.js" type="module"></script>␊
</body></html>`,
},
{
code: undefined,
fileName: 'index.html',
map: undefined,
source: `<html><head>␊
</head>␊
<body>␊
<div id="root"></div>␊
<script src="/admin/app-88ed8fd6.js" type="module"></script>␊
</body></html>`,
},
]

Binary file not shown.

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
// ...

View File

@@ -10,7 +10,10 @@ export const getCode = async (bundle, outputOptions, allFiles = false) => {
const { output } = await bundle.generate(outputOptions || { format: 'cjs', exports: 'auto' });
if (allFiles) {
return output.map(({ code, fileName, source, map }) => {
return output.sort((a,b)=> {
if(a.fileName === b.fileName && a.source !== b.source){ return a.source<b.source?-1:1}
return a.fileName < b.fileName ? -1 : (a.fileName > b.fileName? 1 : 0);
}).map(({ code, fileName, source, map }) => {
return {
code,
fileName,

View File

@@ -0,0 +1,7 @@
<html>
<head>
</head>
<body>
<script src="./watched-file.js" type="module"></script>
</body>
</html>

View File

@@ -0,0 +1,3 @@
export const a = 1; // DO NOT CHANGE ME HERE, but in ../test.js

View File

@@ -0,0 +1,53 @@
# Snapshot report for `test/watch/test.js`
The actual snapshot is saved in `test.js.snap`.
Generated by [AVA](https://avajs.dev).
## watch
> Snapshot 1
[
{
code: undefined,
fileName: 'index.html',
map: undefined,
source: `<html><head>␊
</head>␊
<body>␊
<script src="watched-file-8c4729c5.js" type="module"></script>␊
</body></html>`,
},
{
code: `const a = 2; // If i show up as a changed file, then the watch test has gone wrong!␊
export { a };␊
//# sourceMappingURL=watched-file-8c4729c5.js.map␊
`,
fileName: 'watched-file-8c4729c5.js',
map: SourceMap {
file: 'watched-file-8c4729c5.js',
mappings: 'AACgB,MAAC,CAAC,GAAG,EAAE;;;;',
names: [],
sources: [
'../watched-file.js',
],
sourcesContent: [
`␊
export const a = 2; // If i show up as a changed file, then the watch test has gone wrong!␊
`,
],
version: 3,
},
source: undefined,
},
{
code: undefined,
fileName: 'watched-file-8c4729c5.js.map',
map: undefined,
source: '{"version":3,"file":"watched-file-8c4729c5.js","sources":["../watched-file.js"],"sourcesContent":["\\n export const a = 2; // If i show up as a changed file, then the watch test has gone wrong!\\n "],"names":[],"mappings":"AACgB,MAAC,CAAC,GAAG,EAAE;;;;"}',
},
]

Binary file not shown.

97
test/watch/test.js Normal file
View File

@@ -0,0 +1,97 @@
import {join, dirname} from "node:path";
import test from "ava";
import * as rollup from "rollup";
import {debugPrintOutput, getCode} from "../util/test.js";
import {resolve} from "node:path";
import {writeFile} from "node:fs/promises";
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";
import {pathToFileURL} from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
process.chdir(join(__dirname, 'fixtures'));
test.serial('watch', async (t) => {
const origContent = `
export const a = 1; // DO NOT CHANGE ME HERE, but in ../test.js
`;
const changeContent = `
export const a = 2; // If i show up as a changed file, then the watch test has gone wrong!
`
const path = resolve(__dirname, 'fixtures/watched-file.js');
await writeFile(path, origContent, {encoding: 'utf-8'});
const watcher = rollup.watch({
input: 'index.html',
output,
plugins: [
html({
}),
],
watch: {
skipWrite: true,
}
});
const steps = [
async (bundle)=>{
await writeFile(path, changeContent, {encoding: 'utf-8'});
// Just wait on the watch mode to pick up on the changes
},
async (bundle)=>{
const code = await getCode(bundle, output, true);
debugPrintOutput('watch',code);
// Reset the source file
await writeFile(path, origContent, {encoding: 'utf-8'});
// Assert the output is what we exapect;
t.snapshot(code);
watcher
},
];
await new Promise((resolve, reject)=>{
watcher.on('event', async (event) => {
const {result} = event;
switch (event.code) {
case "START":
t.log(`WATCH STARTED`);
break;
case "BUNDLE_START":
t.log(`REBUILDING...`);
break;
case "BUNDLE_END":
t.log(`Rebuilt...`);
const cb = steps.shift();
const generated = await result.generate(output);
const cbResult = await cb(result);
if(steps.length===0){
watcher.close();
resolve();
}
break;
case "ERROR":
reject(event.error);
break;
}
if (result) {
result.close();
}
});
});
});

24
types/index.d.ts vendored
View File

@@ -15,6 +15,11 @@ export interface RollupHtmlTransformContext {
// 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 interface RollupHtmlOptions {
@@ -23,6 +28,7 @@ export interface RollupHtmlOptions {
* Follows the same logic as rollup's [entryFileNames](https://rollupjs.org/configuration-options/#output-entryfilenames).
*/
htmlFileNames?: string|((chunkInfo: PreRenderedChunk) => string);
/**
* Transform a source file passed into this plugin to HTML. For example: a handlebars transform
* ```
@@ -33,6 +39,17 @@ export interface RollupHtmlOptions {
*/
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.
* 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)
*/
resolve?: ResolveCallback;
/**
* [Pattern](https://github.com/micromatch/picomatch#globbing-features) to include
*/
include?: FilterPattern;
/**
* [Pattern](https://github.com/micromatch/picomatch#globbing-features) to exclude
*/
exclude?: FilterPattern
}