Convert Figma logo to code with AI

requirejs logoalmond

A minimal AMD API implementation for use after optimized builds

2,414
167
2,414
8

Top Related Projects

2,571

Runs RequireJS in Node and Rhino, and used to run the RequireJS optimizer

65,410

A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.

25,839

Next-generation ES module bundler

43,888

The zero configuration build tool for the web. 📦🚀

13,076

Dynamic ES module loader

browser-side require() the node.js way

Quick Overview

Almond is a minimal AMD API implementation for use after optimized builds with RequireJS. It provides a smaller footprint alternative to RequireJS when all modules are bundled into one file, making it ideal for production environments where file size and load times are critical.

Pros

  • Significantly smaller file size compared to full RequireJS (about 1KB minified and gzipped)
  • Compatible with modules built by RequireJS optimizer
  • Allows for a smooth transition from development to production environments
  • Supports loading of named modules and anonymous modules

Cons

  • Does not support dynamic loading of external scripts
  • Limited functionality compared to full RequireJS (e.g., no plugins support)
  • May require additional configuration for complex module dependencies
  • Not suitable for development environments where dynamic loading is needed

Code Examples

  1. Defining a module:
define('myModule', ['dependency1', 'dependency2'], function(dep1, dep2) {
    return {
        doSomething: function() {
            return dep1.method() + dep2.method();
        }
    };
});
  1. Requiring a module:
require(['myModule'], function(myModule) {
    console.log(myModule.doSomething());
});
  1. Using a named module:
define('math', [], function() {
    return {
        add: function(a, b) { return a + b; },
        subtract: function(a, b) { return a - b; }
    };
});

require(['math'], function(math) {
    console.log(math.add(5, 3)); // Outputs: 8
});

Getting Started

  1. Download almond.js from the GitHub repository.
  2. Include almond.js in your HTML file:
<script src="path/to/almond.js"></script>
  1. Use the RequireJS optimizer to bundle your modules into a single file.
  2. Include the bundled file in your HTML after almond.js:
<script src="path/to/almond.js"></script>
<script src="path/to/bundled-modules.js"></script>
  1. Use require() to load your main application module:
<script>
    require(['main'], function(main) {
        // Your application code here
    });
</script>

Competitor Comparisons

2,571

Runs RequireJS in Node and Rhino, and used to run the RequireJS optimizer

Pros of r.js

  • Full-featured AMD module loader with more advanced capabilities
  • Supports server-side JavaScript execution
  • Offers powerful optimization and build tools for production environments

Cons of r.js

  • Larger file size, which may impact load times for smaller projects
  • More complex configuration and setup process
  • Steeper learning curve for developers new to AMD

Code Comparison

r.js:

requirejs.config({
    baseUrl: 'js/lib',
    paths: {
        app: '../app'
    }
});

requirejs(['jquery', 'app/main'], function($, main) {
    // Application logic here
});

Almond:

define('myModule', ['dependency'], function(dependency) {
    return {
        doSomething: function() {
            // Module logic here
        }
    };
});

require(['myModule'], function(myModule) {
    myModule.doSomething();
});

Key Differences

  • r.js provides a more comprehensive AMD implementation, while Almond is a lightweight alternative
  • Almond is designed for optimized builds and doesn't support dynamic loading of modules
  • r.js offers more flexibility and features, but Almond is simpler and more suitable for smaller projects

Use Cases

  • Choose r.js for large-scale applications with complex module dependencies and build requirements
  • Opt for Almond in smaller projects or when you need a minimal AMD-compatible loader for optimized builds
65,410

A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.

Pros of webpack

  • More powerful and flexible, supporting a wider range of module formats and asset types
  • Built-in code splitting and lazy loading capabilities
  • Extensive plugin ecosystem for additional functionality

Cons of webpack

  • Steeper learning curve and more complex configuration
  • Larger bundle size for small projects
  • Slower build times, especially for large applications

Code comparison

almond:

require.config({
    baseUrl: 'js/lib',
    paths: {
        app: '../app'
    }
});

require(['app/main']);

webpack:

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

Summary

webpack is a more comprehensive and powerful module bundler, offering advanced features like code splitting and support for various asset types. It's well-suited for large, complex applications but may be overkill for smaller projects. almond, on the other hand, is a lightweight AMD loader that's simpler to set up and use, making it a good choice for smaller projects or those primarily using AMD modules. webpack's configuration is more complex but offers greater flexibility, while almond's setup is straightforward but limited in scope.

25,839

Next-generation ES module bundler

Pros of Rollup

  • Tree-shaking: Rollup eliminates unused code, resulting in smaller bundle sizes
  • ES module support: Native handling of ES6+ modules for modern JavaScript
  • Plugin ecosystem: Extensive plugin support for various transformations and optimizations

Cons of Rollup

  • Learning curve: More complex configuration compared to Almond's simplicity
  • Limited CommonJS support: Requires plugins for full CommonJS compatibility

Code Comparison

Almond (AMD-style module):

define(['dependency'], function(dependency) {
  return {
    doSomething: function() {
      dependency.use();
    }
  };
});

Rollup (ES module):

import { use } from 'dependency';

export function doSomething() {
  use();
}

Summary

Rollup excels in modern JavaScript development with its tree-shaking capabilities and ES module support, making it ideal for projects prioritizing bundle size optimization. Almond, on the other hand, offers a simpler setup for AMD-style modules and legacy codebases. While Rollup provides more advanced features and a robust plugin ecosystem, it may require additional configuration and has a steeper learning curve compared to Almond's straightforward approach.

43,888

The zero configuration build tool for the web. 📦🚀

Pros of Parcel

  • Zero configuration required for most projects, making it easier to set up and use
  • Supports a wide range of file types and assets out of the box
  • Offers fast build times with built-in caching and multi-core processing

Cons of Parcel

  • Larger bundle size compared to Almond, which may impact load times
  • Less control over the bundling process, which can be limiting for complex projects
  • Steeper learning curve for customization and advanced configurations

Code Comparison

Almond (AMD module):

define(['jquery'], function($) {
  return {
    init: function() {
      $('body').text('Hello, Almond!');
    }
  };
});

Parcel (ES6 module):

import $ from 'jquery';

export function init() {
  $('body').text('Hello, Parcel!');
}

Summary

Parcel is a modern, zero-configuration bundler that offers ease of use and broad asset support, while Almond is a lightweight AMD loader optimized for small, single-file builds. Parcel excels in simplicity and versatility, whereas Almond shines in scenarios requiring minimal overhead and fine-grained control over module loading.

13,076

Dynamic ES module loader

Pros of SystemJS

  • More flexible and supports multiple module formats (CommonJS, AMD, ES6)
  • Dynamic loading of modules at runtime
  • Better suited for large-scale applications with complex dependencies

Cons of SystemJS

  • Larger file size and potentially slower initial load times
  • Steeper learning curve due to more complex configuration options
  • May require additional setup for optimal performance

Code Comparison

Almond (AMD-style module):

define(['dependency'], function(dependency) {
  return {
    doSomething: function() {
      dependency.use();
    }
  };
});

SystemJS (ES6-style module):

import dependency from 'dependency';

export function doSomething() {
  dependency.use();
}

Summary

Almond is a lightweight AMD loader, ideal for smaller projects or those already using RequireJS. It's simpler to set up but limited to AMD modules. SystemJS offers more flexibility and features, supporting multiple module formats and dynamic loading, making it better suited for larger, more complex applications. However, this comes at the cost of a larger file size and potentially more complex configuration. The choice between the two depends on project requirements, size, and complexity.

browser-side require() the node.js way

Pros of Browserify

  • Allows use of Node.js-style require() statements in browser code
  • Supports a wide range of transforms for preprocessing files
  • Bundles all dependencies into a single file, reducing HTTP requests

Cons of Browserify

  • Requires a build step, which can slow down development
  • May produce larger bundle sizes compared to Almond
  • Learning curve for developers not familiar with Node.js module system

Code Comparison

Almond:

define(['module1', 'module2'], function(module1, module2) {
  // Module code here
});

Browserify:

var module1 = require('module1');
var module2 = require('module2');
// Module code here

Key Differences

Almond is a lightweight AMD loader, designed to be used with optimized RequireJS projects. It's ideal for small to medium-sized projects that don't require dynamic loading.

Browserify, on the other hand, is a more comprehensive tool that allows developers to use Node.js-style modules in the browser. It's better suited for larger projects with complex dependency trees and those that want to leverage the vast ecosystem of npm packages.

While Almond focuses on AMD modules, Browserify uses the CommonJS module format, which may be more familiar to developers with Node.js experience.

Ultimately, the choice between Almond and Browserify depends on the project's specific needs, the development team's preferences, and the existing codebase structure.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

almond

A replacement AMD loader for RequireJS. It provides a minimal AMD API footprint that includes loader plugin support. Only useful for built/bundled AMD modules, does not do dynamic loading.

Why

Some developers like to use the AMD API to code modular JavaScript, but after doing an optimized build, they do not want to include a full AMD loader like RequireJS, since they do not need all that functionality. Some use cases, like mobile, are very sensitive to file sizes.

By including almond in the built file, there is no need for RequireJS. almond is around 1 kilobyte when minified with Closure Compiler and gzipped.

Since it can support certain types of loader plugin-optimized resources, it is a great fit for a library that wants to use text templates or CoffeeScript as part of their project, but get a tiny download in one file after using the RequireJS Optimizer.

If you are building a library, the wrap=true support in the RequireJS optimizer will wrap the optimized file in a closure, so the define/require AMD API does not escape the file. Users of your optimized file will only see the global API you decide to export, not the AMD API. See the usage section below for more details.

So, you get great code cleanliness with AMD and the use of powerful loader plugins in a tiny wrapper that makes it easy for others to use your code even if they do not use AMD.

If you want a single file build output but without the module APIs included, you might want to consider AMDclean.

Restrictions

It is best used for libraries or apps that use AMD and:

  • optimize all the modules into one file -- no dynamic code loading.
  • all modules have IDs and dependency arrays in their define() calls -- the RequireJS optimizer will take care of this for you.
  • only have one requirejs.config() or require.config() call.
  • the requirejs.config/require.config call needs to be included in the build output. This is particularly important for making sure any map config use still works.
  • do not use the var require = {}; style of passing config.
  • do not use RequireJS multiversion support/contexts.
  • do not use require.toUrl() or require.nameToUrl().
  • do not use packages/packagePaths config. If you need to use packages that have a main property, volo can create an adapter module so that it can work without this config. Use the amdify add command to add the dependency to your project.

What is supported:

  • dependencies with relative IDs.
  • define('id', {}) definitions.
  • define(), require() and requirejs() calls.
  • loader plugins that can inline their resources into optimized files, and can access those inlined resources synchronously after the optimization pass. The text and CoffeeScript plugins are two such plugins.

Download

Latest release

Usage

Download the RequireJS optimizer.

Download the current release of almond.js.

Run the optimizer using Node (also works in Java):

node r.js -o baseUrl=. name=path/to/almond include=main out=main-built.js wrap=true

This assumes your project's top-level script file is called main.js and the command above is run from the directory containing main.js. If you prefer to use a build.js build profile instead of command line arguments, this RequireJS optimization section has info on how to do that.

wrap=true will add this wrapper around the main-built.js contents (which will be minified by UglifyJS:

(function () {
    //almond will be here
    //main and its nested dependencies will be here
}());

If you do not want that wrapper, leave off the wrap=true argument.

These optimizer arguments can also be used in a build config object, so it can be used in runtime-generated server builds.

Triggering module execution

As of RequireJS 2.0 and almond 0.1, modules are only executed if they are called by a top level require call. The data-main attribute on a script tag for require.js counts as a top level require call.

However with almond, it does not look for a data-main attribute, and if your main JS module does not use a top level require() or requirejs() call to trigger module loading/execution, after a build, it may appear that the code broke -- no modules execute.

The 2.0 RequireJS optimizer has a build config, option insertRequire that you can use to specify that a require([]) call is inserted at the end of the built file to trigger module loading. Example:

node r.js -o baseUrl=. name=path/to/almond.js include=main insertRequire=main out=main-built.js wrap=true

or, if using a build config file:

{
    baseUrl: '.',
    name: 'path/to/almond',
    include: ['main'],
    insertRequire: ['main'],
    out: 'main-built.js',
    wrap: true
}

This will result with require(["main"]); at the bottom of main-built.js.

Exporting a public API

If you are making a library that is made up of AMD modules in source form, but will be built with almond into one file, and you want to export a small public API for that library, you can use the wrap build config to do so. Build config:

{
    baseUrl: '.',
    name: 'path/to/almond',
    include: ['main'],
    out: 'lib-built.js',
    wrap: {
        startFile: 'path/to/start.frag',
        endFile: 'path/to/end.frag'
    }
}

Where start.frag could look like this:

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        //Allow using this built library as an AMD module
        //in another project. That other project will only
        //see this AMD call, not the internal modules in
        //the closure below.
        define([], factory);
    } else {
        //Browser globals case. Just assign the
        //result to a property on the global.
        root.libGlobalName = factory();
    }
}(this, function () {
    //almond, and your modules will be inlined here

and end.frag is like this:

    //The modules for your project will be inlined above
    //this snippet. Ask almond to synchronously require the
    //module value for 'main' here and return it as the
    //value to use for the public API for the built file.
    return require('main');
}));

After the build, then the built file should be structured like so:

  • start.frag
  • almond.js
  • modules for your lib, including 'main'
  • end.frag

License

MIT

Code of Conduct

jQuery Foundation Code of Conduct.

Common errors

Explanations of common errors:

incorrect module build, no module name

In almond 3.0.0 and earlier, this would show up as "deps is undefined", where this line is mentioned:

if (!deps.splice) {

In 3.0.1+ the error is explicitly: "incorrect module build, no module name".

This means that there is a define()'d module, but it is missing a name, something that looks like this:

define(function () {});
//or
define([], function () {});

when it should look like:

define('someName', function () {});
//or
define('someName', [], function () {});

This is usually a sign that the tool you used to combine all the modules together did not properly name an anonymous AMD module.

Multiple modules built into a single file must have names in the define calls. Otherwise almond has no way to assign the module to a name key for use in the code.

The fix is to use a build tool that understand AMD modules and inserts the module IDs in the build. The requirejs optimizer is a build tool that can do this correctly.

x missing y

It means that module 'x' asked for module 'y', but module 'y' was not available.

This usually means that 'y' was not included in the built file that includes almond.

almond can only handle modules built in with it, it cannot dynamically load modules from the network.

No y

It means that a require('y') call was done but y was not available.

This usually means that 'y' was not included in the built file that includes almond.

almond can only handle modules built in with it, it cannot dynamically load modules from the network.

How to get help

Contributing

Almond follows the same contribution model as requirejs and is considered a sub-project of requirejs.

NPM DownloadsLast 30 Days