在库中获取文件(汇总)
Fetch file in library (rollup)
我正在构建 javascript 库(更多类似小部件的东西),其中将包含一些 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 吗?或者,如果没有 - 我还有哪些其他选择,典型的方法是什么?
您可以直接使用 rollup-plugin-html import
文件而不是获取文件。
设置 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)
}
}
Rollup 现在将捆绑 html 个文件。
我正在构建 javascript 库(更多类似小部件的东西),其中将包含一些 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 吗?或者,如果没有 - 我还有哪些其他选择,典型的方法是什么?
您可以直接使用 rollup-plugin-html import
文件而不是获取文件。
设置 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)
}
}
Rollup 现在将捆绑 html 个文件。