I'm building javascript library (more something like widget) which will have some UI within. I'm adding HTML elements to DOM by javascript. To add this HTML I have following code:
async insertWidgetMarkup() {
try {
const response = await fetch('src/html/form.html')
this.rootElement.innerHTML = await response.text()
} catch (e) {
console.error('Error gathering form HTML.', e)
}
}
I build entire thing with rollup
// rollup.config.js
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'main.js',
output: {
dir: 'dist',
format: 'cjs',
name: 'search_widget.js'
},
plugins: [commonjs()]
};
// package.json
"scripts": {
"build": "rollup --config --watch",
My issue is that in bundled file I have await fetch('src/html/form.html');
therefore it won't work in other applications. Can I somehow tell rollup to resolve this so it will have HTML in bundled file? Or if no - what other options I have, what is typical approach for that?
Instead of fetching, you can import
the file directly with the rollup-plugin-html.
Setup rollup
config to use the plugin like this
import commonjs from '@rollup/plugin-commonjs';
import html from 'rollup-plugin-html';
export default {
input: 'main.js',
output: {
format: 'umd',
name: 'search_widget',
file: 'dist/search_widget.js'
},
plugins: [
commonjs(),
html({
include: '**/*.html'
})
]
};
Then in your source file, use import like this
import html from 'src/html/form.html'
insertWidgetMarkup() {
try {
this.rootElement.innerHTML = html
} catch (e) {
console.error('Error gathering form HTML.', e)
}
}
Rollup will bundle the html files now.