尽管@Jason Miller 的回答对我有很大帮助,但我仍然难以制作一个基本的工作示例,所以这是我从头到尾解决这个问题的方法:
我的基本html
文档包括dummy.js
包含我的虚拟 Web 组件的实际代码的捆绑脚本:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<script async src="./dummy.js" type="text/javascript"></script>
<dummy-view name="Test"></dummy-view>
</div>
</body>
</html>
我的虚拟网络组件:
import {div} from '../utils/hyperscript';
import registerCustomElement from 'preact-custom-element';
const DummyView = ({ name = "World" }) => (
div({}, `Hello, ${name}!`)
);
registerCustomElement(DummyView, "dummy-view", ["name"]);
我的 webpack 配置:
const path = require('path');
module.exports = {
entry: {
dummy: './lib/dummy/dummy-view.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
output: {
path: path.resolve(__dirname, 'webcomponent/')
}
};
更多细节:
- 我是
preact-custom-element
这样安装的npm i preact-custom-element
。
- 捆绑是使用 webpack 完成的,如下所示
npx webpack
:
- 将
index.html
在/webcomponent
(例如http://localhost:3000/webcomponent/)下提供服务。
- 在浏览器中访问上述 URL 时,结果如下所示:
<div>Hello, Test!</div>
附录: