Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 11, 2020 09:12 pm GMT

Dynamic module import with Stimulus JS

Scoped behavior by default

Being built on top of the mutation observer, Stimulus Controllers are only loaded once a data-controller="my-controller" is visible within the DOM.

This is a great way to scope JS behavior to an element within a page.

With the typical Webpack loader, all the Controllers are bundled within the pack.

// src/application.jsimport { Application } from "stimulus"import { definitionsFromContext } from "stimulus/webpack-helpers"const application = Application.start()const context = require.context("./controllers", true, /\.js$/)application.load(definitionsFromContext(context))

Importing large ES modules

When importing very large JS library you might want to only load them only on pages where the controller is used to avoid loading too much JS on other pages.

One nice feature of Webpack is the ability to dynamically load modules.

Using the lifecycle of Stimulus Controllers you can stick you dynamic import right into the initialize() or connect() function.

Here is and example to dynamically load moment

import { Controller } from "stimulus";export default class extends Controller {  connect() {    import("moment").then(moment => {      this.moment = moment.default;    });  }  doSomething() {    const formatedTime = this.moment().format("dddd, MMMM Do YYYY, h:mm:ss a");  }}

and a working demo


Original Link: https://dev.to/adrienpoly/dynamic-module-import-with-stimulus-js-297g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To