我正在建立一个javascript库(更多的是类似widget的东西),里面会有一些UI。我正在通过javascript向DOM中添加HTML元素。为了添加这些HTML元素,我有以下代码。
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)
}
}
我用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",
我的问题是,在捆绑文件中,我有以下内容 await fetch('src/html/form.html');
因此,它在其他应用程序中无法工作。我能否告诉rollup解决这个问题,使它在捆绑文件中包含HTML?或者如果不能,我还有什么其他选择,典型的方法是什么?
取而代之的是,你可以 import
的文件,直接用 rollup-plugin-html.
设置 rollup
配置使用插件,就像这样
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'
})
]
};
然后在你的源文件中,使用导入这样的方法。
import html from 'src/html/form.html'
insertWidgetMarkup() {
try {
this.rootElement.innerHTML = html
} catch (e) {
console.error('Error gathering form HTML.', e)
}
}
滚动将捆绑html文件了。