knockout-contrib

:metal: KnockoutJS Goodies Monorepo

View the Project on GitHub Profiscience/knockout-contrib

component-loader

Version Dependency Status Peer Dependency Status Dev Dependency Status Downloads

This package is intended for consumption via the @profiscience/knockout-contrib metapackage

An easier to use component loader for Knockout. Supports lazy-loading and transforming component configs.

Usage

import { ComponentLoader } from '@profiscience/knockout-contrib'

// Knockout component configuration
import appNavComponent from './app-nav'

const manifest = {
  // synchronous component
  'app-nav': {
    template: '...',
    viewModel: class {},
  },

  // lazy-loaded component
  widget: () => import('./widget'),
}

const componentLoader = new ComponentLoader(manifest)

ko.components.loaders.unshift(componentLoader)

with webpack

Webpack’s require has a context method that can be used with a regular expression to automatically load components without having to manually list all of them in the manifest.

For more information, see webpack’s documentation.

const _require = require.context(
  './', // directory
  true, // use subdirectories
  /\.\/[^/_]+\/index\.(j|t)s$/, // all "<component-name>/index.js" (or ts) files relative to the directory argument, omitting those that begin with an underscore
  'lazy' // webpack require mode; see https://webpack.js.org/api/module-methods/#magic-comments
)

const componentLoader = ComponentLoader.fromRequireContext(_require)

with custom component configuration

You may pass a transform option to transform the component config before it is registered.

const manifest = {
  'my-component': {
    template: '...',
  },
}

const componentLoader = new ComponentLoader(manifest, {
  transform: (component) => {
    component.template = `<span style="border: 1px solid red">${component.template}</span>`
    return component
  },
})