npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

async-usage

v2.2.0

Published

Declarative dynamic imports for everyone!

Downloads

54

Readme

What is it?

This is a simple tool for creating environment specific dynamic import factories with pluginable functionality. It allows you to create dynamic import factories to help your project be KISS and DRY. 😉

You can use it to reduce code repetition in your project's imports.

Mostly designed to work with webpack, but can be easily tuned to work with other bundlers or even native browser dynamic imports.

TLDR

General usage

It's simple - just create your specific async chunk use-case:

// Import the `createAsyncUsage` function
import { createAsyncUsage } from 'async-usage';

// Define the factory function to generate your imports
const importFactory = (path) => import(
  // Baked in webpack's "magic comments"
  /* webpackChunkName: "[request]" */
  /* webpackMode: "lazy" */

  // If using webpack, always start your factory path with a constant string,
  // so that webpack knows where to look to avoid complete module bundling.
  '@/' + path
);

// Create your final usage function
const useComponents = createAsyncUsage(
  importFactory, // Pass the import factory as the 1-st argument
  'components'   // Pass the base path as the second argument
);

And then use it 😉:

const components = useComponents(
  // Object options:
  // key - final imported module name alias
  // value - path to the module, relative to the base path passed into `createAsyncUsage`
  {
    'cool-component-base': 'path/to/cool/component-base',
    'some-component-top': 'path/to/some/component-top',
    'other-component': 'other/component',
  }

// You can then chain the call to avoid unnecessary object spreads
// Aliases for chaining: 'and', 'with'
).and(
  // Array options:
  // value - both path to the module AND its imported alias
  // `/` in the path will be replaced with `-` for the module alias
  [
    'home/page-slider'
  ],
  // Optional absolute path to the module from your importFactory root.
  'pages/home/components'
).clean();


// Result:
components === {
  'cool-component-base': () => import(
    /* webpackChunkName: "[request]" */
    /* webpackMode: "lazy" */
    '@/components/path/to/cool/component-base'
  ),
  'some-component-top': () => import(
    /* webpackChunkName: "[request]" */
    /* webpackMode: "lazy" */
    '@/components/path/to/some-component-top'
  ),
  'other-component': () => import(
    /* webpackChunkName: "[request]" */
    /* webpackMode: "lazy" */
    '@/components/other/component'
  ),
  'home-page-slider': () => import(
    /* webpackChunkName: "[request]" */
    /* webpackMode: "lazy" */
    '@/pages/home/components/home/page-slider'
  )
}

Plugins

It's possible to create custom plugins for createAsyncUsage.

createAsyncUsage already comes with two default plugins you can use: cachePlugin and ProfilePlugin

Shortly, the general format for plugins is the following:

type Plugin = {
  // Called when the usage was just initiated, returning a factory function
  invoked: (path: string, name: string, previousChunk: Promise<Chunk> | undefined) => Promise<Chunk> | undefined;
  
  // Called right before the `import` function is called
  beforeStart: (path: string, name: string, previousChunk: Promise<Chunk> | undefined) => Promise<Chunk> | undefined;

  // Called right after the `import` function is called
  started: (path: string, name: string, newChunk: Promise<Chunk>) => Promise<Chunk> | undefined;

  // Triggered upon successful chunk loading
  resolved: (path: string, name: string, result: Chunk) => Promise<Chunk> | Chunk | undefined;

  // Triggered if there was an error loading a chunk
  rejected: (path: string, name: string, reason) => Promise<Chunk> | Chunk | undefined;
}

Any value returned from those functions that is different from undefined will be treated as a loading result and returned instead of the the original result. If you want to simply let async-usage do its thing - simply return undefined from plugin's function.

Cache Plugin

This plugin simply caches your chunks in-memory, bypassing the browser request cache.

Useful in case of having a 'no-cache' flag for some assets, while also having a need to conditionally cache some modules.

Usage:

import { cachePlugin } from 'async-usage';

const use = createAsyncUsage(/* import factory here */, {
  basePath: 'assets',
  plugins: [
    cachePlugin
  ]
});

Profile Plugin

Logs chunk-loading statistics into the console in a following format:

 ┌─ Loading time from chunk being requested to a fully loaded chunk
 │             ┌─ Status of loading the chunk - Loaded | Error | Cached (loaded from cache by cachePlugin)
 │       ┌─────┴─────┐
250 ms ┬ Chunk loaded: footer-sama  ────── Name of the chunk (ususally, the key in a chunk-path map)
       └─ components/footer-sama
          └─────────┬──────────┘
                    └─ Path to the chunk
                       (relative to the base path set in your custom import factory)

Usage:

import { ProfilePlugin } from 'async-usage';

const use = createAsyncUsage(/* import factory here */, {
  basePath: 'assets',
  plugins: [
    new ProfilePlugin('src/assets', 'color: red')
  ]
});