'How to import HTML as a string with ParcelJS

I'd like to import HTML files as a string with ParcelJS, like this:

import testHTML from './testHTML.html';

document.body.insertAdjacentHTML('afterbegin', testHTML);

But the docs say:

Importing HTML in JavaScript does not statically include the HTML strings, but the HTML files will dynamically be fetched using the Fetch API.

Is there any way to force the import as a string?



Solution 1:[1]

Following up after a few days - it didn't seem possible. RollupJS had this ability though.

Solution 2:[2]

If you are using rollup as module bundle, this plugin rollup-plugin-html will allow you to import a html file as string:

rollup.config.js

import htmlLoader from "rollup-plugin-html";

plugins: [
  ...
    htmlLoader({
      include: "**/*.html",
    }),
  ...
]

Then:

import testHTML from './testHTML.html';

document.body.insertAdjacentHTML('afterbegin', testHTML);

Solution 3:[3]

import html from 'bundle-text:./index.pug';
document.body.innerHTML = html;

so, html is fine too

without any configurations

import html from 'bundle-text:./index.html';
document.body.innerHTML = html;

typescript fix ts(2307)

like "*.vue"

// index.d.ts
declare module 'bundle-text:*' {
    const s: string
    export default s
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 docta_faustus
Solution 2
Solution 3 qwabra