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

als-require

v2.1.0

Published

A utility for using CommonJS require in the browser and creating bundles.

Downloads

286

Readme

als-require

als-require is a lightweight utility that enables the importation and modification of CommonJS modules before execution in both browser and Node.js environments.

Capabilities of als-require:

  • Utilize CommonJS modules in the browser, complete with all dependencies and access to module functionalities.
  • Employ a unified context object across all modules.
  • Modify the code of each module before it is executed.
  • Build minified (optional) bundle for browser

Installation

To install als-require, use npm:

npm install als-require

Importing

Import in nodejs:

const Require = require('als-require')
const module = Require.getModule('./some/path')

Import in browser:

<script src="/node_modules/als-require/require.js"></script>
or
<script src="/node_modules/als-require/require.min.js"></script>

<script>
   Require.version = '1.0'; // optional - adding version when fetching files
   Require.cyclicDependencies = true // false by default
   Require.logger = console // console by default
   Require.getModule('./some/path')
   .then(module => {/* code */})

   // or 
   require('./some/path')
   .then(module => {/* code */})

</script>

Usage

als-require has two files for NodeJS and browser which has same structure and api. Each file includes Require class with folowing structure:

class Require {
   static getModule(path, context) {}
   static contents = {}
   static cyclicDependencies = false // allow cyclic dependencies
   static logger = console // logger for logger.warn
   static bundleName = 'renderedBundle'; // variable name for bundle
   static contextName = 'context';
   static minified = false

   constructor(path) {
      this.contents = {}
      this.path = path
      this.fullPath
      this.contentReady = false
   }
   
   // returns promise in browser
   getContent() {}
   
   // returns result
   build(context = {}, scriptBefore, scriptAfter, modules = {}) {}

   // only in nodejs version. returns bundle
   bundle(context = {}, scriptBefore, scriptAfter) {}
}

const require = Require.getModule // in browser

The structure above describes only properties and methods for usage, without additional properties and methods which used as private methods.

Arguments:

  • path (String): relative path to module for require
  • context (Object): shared object which will be available in all modules

Here explanation what each method and property used for:

  • Require.contextName (String): Name for context variable (default context)

  • Require.getModule - quick way to get contents and build them in one step

    • returns new instance of Requires with ready contents, modules and result
    • The method is sync for NodeJS and async for browser
  • Require.contents - includes modules contents and their children list and used as cache

  • require.getContent() - used for reading module file's contents

    • Adding content to Require.contents and to require.contents
    • The browser version is async and NodeJS version is sync
  • require.build(modules,context,contextName) - builds all modules results

    • return main module result (export) after build
    • add to modules obejct all module's results after build
  • Require.minified: minify the bundle (default false)

  • Require.bundleName: defines variable and assigns bundle result to it

    • if Require.bundleName not defined or equals to '', no assignment
  • bundle - returns bundle inside (function() {})()

    • scriptBefore - Additional script to execute before bundle created (default '')
    • scriptAfter - Additional script to execute after bundle created (default '')
      • script will get access to context, modules and result after creation, but before returning the result
    • context - The context for build in bundle (default empty object)

Node.Js

const Require = require('als-require')
const mod = new Require('./relative/path/to/module')
mod.getContent() // reading all modules
for(const path in mod.contents) {
   mod.contents[path] = mod.contents[path] // modify if needed
}
const context = {} // shared object for all modules empty object by default
const modules = {} // will include all module`s results {relativePath:moduleResult,...}
const scriptBefore = "const SomeVariableAvailableForAllModules = 'Hello';"
const scriptAfter = "console.log('All done!');"
const result = mod.build(context,scriptBefore,scriptAfter,modules) // build the result
const bundle = mod.build(context,scriptBefore,scriptAfter,modules) // build the bundle

Browser

<script src="/node_modules/als-require/require.js"></script>
<script>
   const mod = new Require('./relative/path/to/module')
   const promise = mod.getContent() // fetching all modules
   promise.then(mod => {
      for(const path in mod.contents) {
         mod.contents[path] = mod.contents[path] // modify if needed
      }
      const modules={}, context = {};
      const scriptBefore = "const SomeVariableAvailableForAllModules = 'Hello';"
      const scriptAfter = "console.log('All done!');"

      const result = mod.build(context,scriptBefore,scriptAfter,modules) // build the result
   })
</script>

Require node_modules packages and node modules

In case of path which not starts with ., Require will look for file in node_modules (by checking in package.json). If such package not found (for example require('fs')), result for this package will return null.

const somePackage = require('some-package');
const somePackage1 = require('./node_modules/some-package/index.js');
const fs = require('fs');

module.exports = {somePackage,somePackage1,fs}

In case above somePackage and somePackage1 should return the package, but fs, should return null.

Pay attention, using './node_modules/some-package/index.js' instead 'some-package', you save extra request/readFile for looking the filename.

Context Usage

The context object is a shared space accessible by all modules loaded by als-require. This allows modules to read and write shared data, enabling more interactive and dynamic module behaviors.

Make sure you are using the context for static value (like constants and common variables and functions) and not dynamic, cause it available to all require's results.