esbuild-plugin-html-modules

raw JSON →
0.9.1 verified Fri May 01 auth: no javascript

An esbuild plugin that enables loading HTML files as ES modules, following the WICG HTML Modules proposal. Version 0.9.1 allows importing HTML files with `import` statements, where the HTML template becomes the default export and `<script type="module">` code runs as the module script. Supports configuration for global CSS extraction, local style transformation via PostCSS, and custom file filters. Key differentiator: enables web component authors to co-locate templates, scripts, and styles in single HTML files with standard ES module semantics. Released weekly, actively maintained.

error Cannot find module 'esbuild-plugin-html-modules'
cause Package not installed or missing from dependencies.
fix
Run npm install esbuild-plugin-html-modules --save-dev.
error TypeError: htmlModulesPlugin is not a function
cause Using CJS `require` without `.default`.
fix
Change to const htmlModulesPlugin = require('esbuild-plugin-html-modules').default;
breaking The `extractScopedStyles: true` option was removed in v0.8. Use `extractGlobalStyles` or shadow DOM styles instead.
fix Replace `extractScopedStyles: true` with `extractGlobalStyles: true` and use standard CSS nesting or `@scope` for scoped styles.
deprecated The default export `htmlModulesPlugin` is deprecated in favor of the named export. The default export will be removed in v1.0.
fix Use `import { htmlModulesPlugin } from 'esbuild-plugin-html-modules'` instead of the default import.
gotcha CJS require must use `.default` property to access the plugin function.
fix Use `const htmlModulesPlugin = require('esbuild-plugin-html-modules').default;`
gotcha The `filter` option must be a RegExp. Passing a string will cause unexpected behavior.
fix Use a RegExp, e.g., `filter: /\.html$/`.
npm install esbuild-plugin-html-modules
yarn add esbuild-plugin-html-modules
pnpm add esbuild-plugin-html-modules

Shows how to set up esbuild with htmlModulesPlugin, including global style extraction and local style transformation with PostCSS.

// quickstart.js
import * as esbuild from 'esbuild';
import htmlModulesPlugin from 'esbuild-plugin-html-modules';

await esbuild.build({
  bundle: true,
  entryPoints: ['src/index.js'],
  outfile: 'dist/bundle.js',
  plugins: [
    htmlModulesPlugin({
      filter: /\.html$/,
      experimental: {
        extractGlobalStyles: true,
        transformLocalStyles: async (css, { filePath }) => {
          // Example: use PostCSS for transformation
          const postcss = (await import('postcss')).default;
          const result = await postcss([
            require('autoprefixer')
          ]).process(css, { from: filePath });
          return result.css;
        }
      }
    })
  ]
});

console.log('Build complete!');