liveBook · Manning

Import statement

As explained in Web Components in Action

A JavaScript module declaration that makes exported bindings from another module available in the current module.

A page with several Web Components can become a fragile stack of script references. JavaScript modules let the page load one entry file while each component imports the dependencies it needs. An import statement names another module and, when importing an export, makes that binding available in the current module. section 5.2

Follow a component dependency

The application module imports its string-container component: import Strings from '../strings/strings.js';. The container then imports the default-exported string class from '../string/string.js'. That string module also registers the custom element used by the container. The HTML page needs only the application module as its JavaScript entry point. section 5.2

Listing 5.8. The Web Harp application Web Component
// file: components/app/app.js

import Strings from '../strings/strings.js';

export default class WebHarpApp extends HTMLElement {
   connectedCallback() {
       this.innerHTML = '<webharp-strings strings="' +
         this.getAttribute('strings') + '"></webharp-strings>';
   }
}
if (!customElements.get('webharp-app')) {
   customElements.define('webharp-app', WebHarpApp);
}

The application component imports its child component, then renders that child as a custom element. section 5.2

This is a different approach from HTML Imports, which were proposed for bringing component markup and logic into a document but never became a standard. Module imports can also let a component take just the library it needs rather than requiring the page to load an entire framework. For older-browser or production builds, bundling can combine files while leaving out unused imports. section 1.1 section 1.2 section 12.6

How Web Components in Action covers it

How deep it goes
Works through a multi-component import chain but defers a deeper introduction to modules.
Examples
Uses a browser harp whose application imports a string container, which imports an individual string component.
What it assumes
Assumes familiarity with basic JavaScript and custom elements; directs readers needing a deeper module introduction to an appendix.
What you can do after
Build it from scratch as a Web Component dependency chain with one JavaScript module entry in the HTML page.
How it connects
Connects JavaScript modules and custom elements while distinguishing module imports from the abandoned HTML Imports proposal.

Also explained in

Compare how 13 books explain import statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.