Search code examples
javascripthtmlweb-component

Combining Web Component Script References Within a Single File


I have successfully implemented web components into my application, which has cut down on the length of the index.html file considerable. The only part that bugs me at this point is the lengthy list of web component script references, like so:

  <script src="web-components/ScheduleManager.js"></script>
  <script src="web-components/ActionButtons.js"></script>
  <script src="web-components/DetailsPane.js"></script>
  <script src="web-components/PageHeaderLinks.js"></script>
  <script src="web-components/SideBarHeader.js"></script>
  <script src="web-components/JobsTableHeader.js"></script>
  <script src="web-components/ModuleMenus.js"></script>
  <script src="web-components/SelectDetailsPane.js"></script>
  //... more web components

What I'm looking for is a simple way to group these web components in a separate file, and then import that one file into my index.html file, just so I don't have so many of these <script> references on the index.html page itself, which I'm trying to keep terse.

What is the simplest way to accomplish this? I don't need additional pre-processing. Just a simple way to group these web components into a single <script> reference, or something similar.


Solution

  • Simply import them as ES Modules. Create a file components.js right next to your index.html:

    import { ScheduleManager } from 'web-components/ScheduleManager.js';
    import { ActionButtons } from 'web-components/ActionButtons.js';
    import { DetailsPane } from 'web-components/DetailsPane.js';
    import { PageHeaderLinks } from 'web-components/PageHeaderLinks.js';
    import { SideBarHeader } from 'web-components/SideBarHeader.js';
    import { JobsTableHeader } from 'web-components/JobsTableHeader.js';
    import { ModuleMenus } from 'web-components/ModuleMenus.js';
    import { SelectDetailsPane } from 'web-components/SelectDetailsPane.js';
    

    In your webcomponents files, export the classes, example:

    export class ScheduleManager extends HTMLElement {
    

    Last step: Link the components.js in your HTML with type="module" in the <head>:

    <script src="./components.js" type="module"></script>