terser / html-minifier-terser

actively maintained fork of html-minifier - minify HTML, CSS and JS code using terser - supports ES6 code
https://terser.org/html-minifier-terser
MIT License
376 stars 30 forks source link

How to import into ES6 Module in the Browser? #41

Closed mudgen closed 4 years ago

mudgen commented 4 years ago

Hello, How can I access or import "html-minifier-terser" into my ES6 module so I can use it? This is running in the browser and I am not using a build tool like webpack etc.

DanielRuf commented 4 years ago

html-minifier and html-minifier-terser use the exports variant so this it is not available as ESM but CJS. See https://github.com/DanielRuf/html-minifier-terser/blob/v5.1.1/src/htmlminifier.js#L1351

mudgen commented 4 years ago

I figured out how to make the original https://github.com/kangax/html-minifier library work in an ES6 module in the browser. Just doing this works:

const htmlMinify = window.require('html-minifier').minify;

Because the library makes "require" a global variable in the browser.

DanielRuf commented 4 years ago

const htmlMinify = window.require('html-minifier').minify;

Yes, but this is not an ESM import. What you do is mixing ESM with CJS. https://github.com/kangax/html-minifier/blob/gh-pages/package.json#L41

Because the library

This is only the case in the dist files as browserify is used and this should not be the way to go (in an ideal case): https://github.com/kangax/html-minifier/blob/gh-pages/Gruntfile.js#L29

For true ES6 imports and module support with treeshaking support and ES6 code we have to introduce an additional setup in the future. For example with rollup to generate an ESM bundle that you can natively consume.

DanielRuf commented 4 years ago

As html-minifier-terser is a fork of html-minifier you can use the same solution if you are ok with mixing require and import or ES5 and ES6 code.

mudgen commented 4 years ago

Thanks for the info.

DanielRuf commented 4 years ago

Closing as resolved.