asyncliz / rollup-plugin-minify-html-literals Goto Github PK
View Code? Open in Web Editor NEWRollup plugin to minify HTML template literal strings
License: MIT License
Rollup plugin to minify HTML template literal strings
License: MIT License
Hello there! I've realized the produced out, given the following input, might create unexpected results:
const scope = {};
render(el, html`<App .scope=${scope}/>`);
The observed result is that <App .scope=${scope}/>
becomes <App .scope=${scope}/ ></App>
, but things get even more interesting when there is a space after scope
:
const scope = {};
render(el, html`<App .scope=${scope} />`);
That would be converted into <App .scope=${scope}>
, removing the self closing tag, hence breaking libraries capable of dealing with it, such as lighterhtml, neverland, or heresy, which is kinda of a bummer, because by design these libraries simplify Custom Elements tag writing, without needing to close empty elements, either as divs, used to decorate, or custm_elements.
Unfortunately, this means I should suggest to avoid this plugin with those libraries, as it can have undesired side-effects if people write simplified HTML tags, without these needing necessarily to be void tags.
Is it reasonable to ask to add an option to leave the self closing />
, either with, or without a space before, untouched? That would make this awesome tool usable to produce minified components for pretty much all of my libraries.
Thanks in advance for any sort of outcome, and for eventually considering adding this extra option.
import minifyHTML from 'rollup-plugin-minify-html-literals';
const bundle = await rollup.rollup({
input: `${roots.js}/src/components/**/*.ts`,
output: {
file: out,
format: "es",
sourcemap: true
},
plugins: [
multi(),
resolve(),
minifyHTML(),
esbuild({
tsconfig: "./tsconfig.json",
minify: true,
}),
]
});
Is this intentional?
I am trying this out and find it only works if my tagged template literals don't have a <style>
element inside them. If I add <style>
, I end up with \n
and spaces in my bundle. If I remove it, \n
and spaces go away. Add it back, they come back. It repeats reliably.
But the documentation of https://github.com/asyncLiz/minify-html-literals shows an example that minifies and includes <style>
...?
PS: This is different from the CSS inside the <style>
being minified or not. I mean the whole template literal, not the CSS. (My CSS is minified, but by PostCSS+cssnano, so that's tangential.)
Using the default settings, a variable inside of an HTML comment throws the following error:
UnhandledPromiseRejectionWarning: Error: splitHTMLByPlaceholder() must return same number of strings as template parts
This can be fixed by escaping the $
const { minifyHTMLLiterals } = require('minify-html-literals');
const contents = `
class {
render() {
const myVar = '';
return html\`
<html>
<!-- comment \${myVar} -->
</html>
\`;
}
}
`;
console.log(minifyHTMLLiterals(contents));
input
html`
<style>
--red: ${red};
--blue: ${blue};
--green: ${green};
</style>
`
expecting output to be
`<style>--red:${red};--blue:${blue};--green:${green};</style>`
instead got
`<style>--red:${red}--blue:${blue}--green:${green}</style>`
Hello, please help with the issue.
Plagin do nothing: literal strings are not minified.
cmd:
rollup -c
warning in console:
src/index.js → dist/index.js...
(!) The "transform" hook used by the output plugin minify-html-literals is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.
created dist/index.js in 892ms
rollup v2.63.0
rollup.config.js
import { terser } from 'rollup-plugin-terser';
import minifyHTML from 'rollup-plugin-minify-html-literals';
import { defaultShouldMinify } from 'minify-html-literals';
export default {
input: 'src/index.js',
output: {
file: 'dist/index.js',
format: 'iife',
plugins: [
minifyHTML({
options: {
shouldMinify(template) {
return (
defaultShouldMinify(template) ||
template.parts.some(part => {
return (
part.text.includes('<style')
);
})
);
}
}
}),
terser({
mangle: {
keep_classnames: false,
keep_fnames: false,
properties: {
regex: /^_/
}
}
})
]
}
};
package.json
{
"name": "..",
"version": "1.0.0",
"description": "",
"main": "index.html",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "...",
"license": "...",
"devDependencies": {
"eslint": "^7.32.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.2.0",
"rollup-plugin-minify-html-literals": "^1.2.6",
"rollup-plugin-terser": "^7.0.2"
}
}
Thank you.
When running the plugin on template literals which don’t have a wrapping <html>
tag, the minification does not work unless the tags in question are explicitely allowed through a custom shouldMinify
callback.
The sample code to reproduce this (irrelevant stuff removed):
class MyDemo extends HTMLElement
{
connectedCallback() {
this.shadow.innerHTML = `
<style>
.content {
all: initial;
display: block;
border: 1px dotted #aaa;
padding: 10px;
}
h1 {
margin: 0;
}
ul {
overflow: hidden;
list-style: none;
margin: 15px 0;
padding: 0;
}
li {
float: left;
background: #f1f1f1;
margin: 0 15px 0 0;
padding: 3px 10px;
}
.img {
background: #f3f3f3;
padding: 7px;
display: inline-block;
}
.img p {
margin: 3px 0 0;
}
img {
min-height: 400px;
max-height: 600px;
width: 100%;
}
</style>
<div class="content">
<h1>${this.data.name}</h1>
<ul>${this.data.labels.map(label => `<li title="${label.desc}">${label.title}</li>`).join('')}</ul>
<div class="img">
<img src="${this.data.images[0].url}">
<p>${this.data.images[0].title}</p>
</div>
<p>${this.data.description}</p>
</div>
`
}
}
customElements.define('my-demo', MyDemo)
The template literal does not get minified unless I pass an option like:
shouldMinify(template) {
return (template.parts.some(part => {
return (
part.text.includes('<style') ||
part.text.includes('<div')
)
})
)
}
I’m not sure this is intentional or not; to me it feels like a shortcoming, because it does not support the very common use case of custom elements with Shadow DOM.
At least it might make sense to add an option to the plugin that allows to minify the string even if it’s just a fragment rather than a complete document.
Hi, when minify a css string with @container rules, the output is not correct and the container queries will not work anymore
Decided to try setup project with Yarn 2, but this package fails to install.
Not sure is it related to plugin or Yarn itself, but i will report it.
"rollup": "^1.31.0",
is installed at the time of installing this package.
Original issue can be found there.
yarn add -D rollup-plugin-minify-html-literals
➤ YN0000: ┌ Resolution step
➤ YN0002: │ yarn2-test@workspace:. doesn't provide rollup@^0.65.2 || ^1.0.0 requested by rollup-plugin-minify-html-literals@npm:1.2.2
➤ YN0000: └ Completed in 1.95s
➤ YN0000: ┌ Fetch step
➤ YN0013: │ typescript@patch:typescript@npm%3A2.9.2#builtin<compat/typescript>::version=2.9.2&hash=226bd1 can't be found in the cache and will be fetched from the disk
➤ YN0001: │ Error: typescript@patch:typescript@npm%3A2.9.2#builtin<compat/typescript>::version=2.9.2&hash=226bd1: Cannot apply hunk #1
at c (/usr/local/lib/node_modules/yarn/bin/yarn.js:58:888149)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
at async /usr/local/lib/node_modules/yarn/bin/yarn.js:58:890280
at async o (/usr/local/lib/node_modules/yarn/bin/yarn.js:58:887432)
at async Object.t.applyPatchFile (/usr/local/lib/node_modules/yarn/bin/yarn.js:58:890253)
at async t.PatchFetcher.patchPackage (/usr/local/lib/node_modules/yarn/bin/yarn.js:58:887187)
at async /usr/local/lib/node_modules/yarn/bin/yarn.js:58:886444
at async /usr/local/lib/node_modules/yarn/bin/yarn.js:36:569449
at async /usr/local/lib/node_modules/yarn/bin/yarn.js:36:569392
at async /usr/local/lib/node_modules/yarn/bin/yarn.js:36:570734
➤ YN0000: └ Completed in 7.89s
➤ YN0000: Failed with errors in 9.84s
When installing this plugin with a current rollup version, I get the following warning:
npm WARN [email protected] requires a peer of rollup@^0.65.2 || ^1.0.0 but none is installed. You must install peer dependencies yourself.
Is it true that this plugin is incompatible with rollup ^2.0.0? It appears to be doing its job just fine.
According to Lit docs this package should be installed.
But installation just fails:
$ npm i --save-dev rollup-plugin-minify-html-literals
Result:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/rollup
npm ERR! dev rollup@"^3.20.7" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer rollup@"^0.65.2 || ^1.0.0 || ^2.0.0" from [email protected]
npm ERR! node_modules/rollup-plugin-minify-html-literals
npm ERR! dev rollup-plugin-minify-html-literals@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/bob/.npm/eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/bob/.npm/_logs/2023-04-21T16_53_26_092Z-debug-0.log
Currently dependency doesn't allow working with rollup 3. I don't know if code must be changed too.
Rollup returns
(!) Broken sourcemap
https://rollupjs.org/troubleshooting/#warning-sourcemap-is-likely-to-be-incorrect
Plugins that transform code (such as "minify-html-template-literals") should generate accompanying sourcemaps.
while compiling.
This is my rollup.config:
export default [
{
input: './test-files/input.js',
plugins: [
minifyHTML({
options: {
minifyOptions: {
html5: true,
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
conservativeCollapse: true,
decodeEntities: true,
},
shouldMinify: () => true
}
}),
terser(terserOptions),
],
output: [
{
file: './test-files/output.min.js',
format: 'iife',
sourcemap: true
}
]
}
];
Am I setting something wrong?
Breaks with this message:
(!) Plugin minify-html-literals: splitHTMLByPlaceholder() must return same number of strings as template parts
input.js:
html`
<div style="--xyz: ${a};">
</div>
`;
Fails with this message:
(!) Plugin minify-html-literals: splitHTMLByPlaceholder() must return same number of strings as template parts
in.js:
let a = 5;
html`
<div>
<!-- ${a} -->
</div>
`;
rollup.config.js:
import minifyHTML from 'rollup-plugin-minify-html-literals';
export default {
input: 'in.js',
output: {
file: 'out.js',
format: 'es'
},
plugins: [
minifyHTML()
]
};
Hi! As there are several projects using this npm package, but it not having a release for over 3 years now, I wonder, is there a plan for how maintenance could be passed on to more active developers?
Forks has even started to popup with a separate package name like https://github.com/ouweiya/rollup-plugin-minify-html-literals-v3 .
As Rollup continues to make major releases this package needs to keep releasing at least once for each major release.
Any thoughts about how this could be solved moving on?
I want to use css preprocessor, therefore I have to use custom minifier function, where the last call would be to minify.minifyHTMLLiterals
.
How about making a special function, that accepts next(processedSource)
as a callback, where all the preprocessor stuff would perform? next
would finally call minify.minifyHTMLLiterals
.
Using these versions:
there is a warning on the output and it looks like the template literals are not parsed:
(!) Plugin minify-html-literals: result.matchAll is not a function
This warning doesn't happen using these versions:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.