首页 > 解决方案 > ES5 中的可共享组件

问题描述

Vue、React 和 Angular 等现代 javascript 框架支持在 Web 应用程序中跨页面/模块创建可共享组件。使用 HTML + ES5 实现这一目标的最佳方法是什么?任何库或框架?我正在使用不支持 ES6 的遗留代码

标签: javascriptecmascript-5

解决方案


您可以从 JS 中创建 HTML 元素,并带上一个.css文件用于样式设置或使用 JS 设置样式。然后您只需将其导入到您的 HTML 中,如下所示:

<script src="yourcomponent/index.js"></script>

您还可以使用 acdn来部署您的组件。

组件中的示例index.js

function createRoot() {
  const rootElement = document.createElement("div");

  document.body.appendChild(rootElement);

  return rootElement;
}

function createComponent(root = createRoot(), elementType, className) {
   const componentWrapper = document.createElement(elementType);
   componentWrapper.setAttribute("class", className);

   return componentWrapper;
}


// usage

// you can pass root or not
const component = createComponent(document.getElementById("root"), "div", "my-component-wrapper");

然后,您可以将额外的 DOM 节点附加到它或应用功能。所有这些都可以与您的脚本一起使用。

希望这可以作为灵感:)


推荐阅读