A file and module loader for JavaScript

Related tags

Loaders requirejs
Overview

RequireJS

RequireJS loads plain JavaScript files as well as more defined modules. It is optimized for in-browser use, including in a Web Worker, but it can be used in other JavaScript environments, like Rhino and Node. It implements the Asynchronous Module API.

RequireJS uses plain script tags to load modules/files, so it should allow for easy debugging. It can be used simply to load existing JavaScript files, so you can add it to your existing project without having to re-write your JavaScript files.

RequireJS includes an optimization tool you can run as part of your packaging steps for deploying your code. The optimization tool can combine and minify your JavaScript files to allow for better performance.

If the JavaScript file defines a JavaScript module via define(), then there are other benefits RequireJS can offer: improvements over traditional CommonJS modules and loading multiple versions of a module in a page. RequireJS also has a plugin system that supports features like i18n string bundles, and text file dependencies.

RequireJS does not have any dependencies on a JavaScript framework.

RequireJS works in IE 6+, Firefox 2+, Safari 3.2+, Chrome 3+, and Opera 10+.

Latest Release

License

MIT

Code of Conduct

jQuery Foundation Code of Conduct.

Directories

  • dist: Scripts and assets to generate the requirejs.org docs, and for generating a require.js release.
  • docs: The raw HTML files for the requirejs.org docs. Only includes the body of each page. Files in dist are used to generate a complete HTML page.
  • tests: Tests for require.js.
  • testBaseUrl.js: A file used in the tests inside tests. Purposely placed outside the tests directory for testing paths that go outside a baseUrl.
  • updatesubs.sh: Updates projects that depend on require.js Assumes the projects are siblings to this directory and have specific names. Useful to copy require.js to dependent projects easily while in development.

Tests

This repo assumes some other repos are checked out as siblings to this repo:

git clone https://github.com/requirejs/text.git
git clone https://github.com/requirejs/i18n.git
git clone https://github.com/requirejs/domReady.git
git clone https://github.com/requirejs/requirejs.git

So when the above clones are done, the directory structure should look like:

  • domReady
  • i18n
  • text
  • requirejs (this repo)

You will need to be connected to the internet because the JSONP and remoteUrls tests access the internet to complete their tests.

Serve the directory with these 4 siblings from a web server. It can be a local web server.

Open requirejs/tests/index.html in all the browsers, click the arrow button to run all the tests.

Comments
  • require.js in Google Chrome attempts to load from

    require.js in Google Chrome attempts to load from "modules"

    Downloaded require.js 2.1.8 and setting it up as explained. But for some reason I get the following log output with errors:

    GET http://localhost:8000/modules/main.js 404 (Not Found) 
        skitch.js:379
    Hello require js world! 
        main.js:6
    Uncaught Error: Script error for: main http://requirejs.org/docs/errors.html#scripterror 
        skitch.js:354
    

    screen shot 2013-09-14 at 12 27 03

    What is odd is that modules are loaded and executed as normally, but require attempts to load the same module from a modules path, which doesn't exist and is not set anywhere.

    Here is the main.js and the html used is the exact same as the one used in the getting started page.

    requirejs.config({
        baseUrl: 'scripts/game'
    });
    
    define([], function() {
        console.log('Hello require js world!');
    });
    

    This happens on Mac OS X (10.8.4) in both Chrome (29.0.1547.65) and Chrome Canary (31.0.1630.0). The same page does not throw errors on Safari 6.0.5.

    opened by spoike 45
  • Document how to define a require-config file shared across different scripts

    Document how to define a require-config file shared across different scripts

    Hi,

    The new version of requirejs looks really promising but I have a little issue. Previously I used the !order plugin to load a main config file which was used for the normal page, tests and other places.

    For instance, the file was loaded from the boot.js file : https://github.com/idflood/next-boilerplate.js/blob/master/src/scripts/boot.js And the config file looked like this: https://github.com/idflood/next-boilerplate.js/blob/master/src/scripts/require-config.js

    Now, without the !order plugin this trick doesn't work anymore. I have some ideas about possible solutions but I can't find an elegant one. One easy solution would be to have nested require calls, but if I'm right the r.js optimizer will not really work with that.

    Any idea to solve this in an elegant way?

    opened by idflood 34
  • require.js sometimes throws Load Timeout even though it never started loading the file

    require.js sometimes throws Load Timeout even though it never started loading the file

    I've been able to consistently reproduce a problem where require.js loads modules for 200ms, then sits there until waitSeconds expires and throws an error complaining that a certain module never loaded in time. Thing is, I can see that require.js never even tries to load the module in question.

    Take a look at the log I posted over at https://github.com/guybedford/require-css/issues/177#issuecomment-68548826. Do you think this issue is related to https://github.com/jrburke/requirejs/issues/1046?

    I don't have a minimal testcase for reproducing the problem, but I am able to reproduce it locally fairly consistently. It occurs roughly 10% of the time, so if I run 10 unit tests in a row I tend to run into this bug at least once.

    The posted log doesn't contain timestamp values but shortly after posting the comment I added them by logging var timeElapsed = new Date().getTime() - context.startTime for each line.

    @jrburke I am not going to be able to resolve this without your help. How do I go about debugging this further?

    opened by cowwoc 23
  • urlArgs busts all

    urlArgs busts all

    urlArgs is an ok solution for appending something to the end of a url.

    The problem is that it appends something to all urls, including third party urls.

    So, if I have a path like this:

    require.config({urlArgs: 'v=1', paths: {facebook: 'https://connect.facebook.net/en_US/all'}});
    

    Then it'll append v=1 to the end of that url. Not good since I don't want to cache bust third party urls like that.

    I can see where the fix would be in require.js... shall I submit a pull request?

    opened by lookfirst 23
  • QUnit tests stop running (in PhantomJS) when upgrading from 2.0.6 to 2.1.*

    QUnit tests stop running (in PhantomJS) when upgrading from 2.0.6 to 2.1.*

    Without changing any behaviour in the test suite, simply updating the requirejs library from 2.0.6 to 2.1.* prevents all my tests from running in PhantomJS. (May be linked to #554)

    I've put together a simple test repo to recreate the issue at https://github.com/fabien-d/require-qunit-test.


    Screen Shot 2013-01-31 at 8 00 57 AM

    2.0.6

    Screen Shot 2013-01-31 at 8 04 00 AM

    2.1.4

    Screen Shot 2013-01-31 at 8 05 12 AM

    opened by fabien-d 22
  • shim not working?

    shim not working?

    i'm not sure if it's not working or i'm not getting the API right. here's what my paths looks like:

    paths: {
        // RequireJS plugins
        text   : 'libs/requirejs/plugins/text-2.0.0',
        jadify : 'libs/requirejs/plugins/jadify-0.0.1',
    
        jquery     : 'libs/jquery/jquery-1.7.1',
        underscore : 'libs/underscore/underscore-1.3.1',
        backbone   : 'libs/backbone/backbone-custom.min',
        d3         : 'libs/d3/d3.v2',
        hephaestus : 'libs/hephaestus/hephaestus.min',
        prometheus : 'libs/prometheus',
        jade       : 'libs/jade/jade'
    },
    

    and here's my shim:

    shim : {
        underscore : {
            exports : '_'
        },
    
        backbone : {
            deps : ['underscore', 'jquery'],
            exports : 'Backbone'
        },
    
        hephaestus : {
            deps : ['backbone'],
            exports : 'Hephaestus'
        },
    
        d3 : {
            exports : 'd3'
        },
    
        prometheus : {
            deps : ['d3', 'backbone'],
            exports : 'Prometheus'
        },
    
        jade : {
            exports : 'jade'
        }
    },
    
    • Hephaestus is a Backbone plugin.
    • Prometheus is a D3/Backbone plugin.

    but if i put in breakpoints, hephaestus.min gets run before backbone-custom.min ever does.

    opened by ianstormtaylor 21
  • I want to dynamically create a main.js file which will contain the requirejs config.

    I want to dynamically create a main.js file which will contain the requirejs config.

    I have a json file where i list out all the modules that i want to use in my app and bundle them. So for that i haven't created a main.js file, but i want to create that file dynamically and want to add the paths, shims and other configs dynamically too. So how can i achieve that ? Or is there any way where i can extend the prebuilt config of main.js file and those extra modules Here is my json file which conatins the module paths.

    custom-package.json

    `{ "name": "custom-package,

    "modulePaths:{ "modules": "src/modules" "vendor": "src/vendor" }

    "modules": [ "modules/Application" "modules/Home" "modules/AboutUs" "vendor/Backbone" "vendor/jquery" ] }`

    opened by sohankd 20
  • Performance problems

    Performance problems

    There is an about 2-300 msec gap between loading the configuration file of require.js and loading the first module. Why is that?

    gap

    index.html:

    <!DOCTYPE HTML>
    <html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="skin.css"/>
    </head>
    <body>
    <script src="lib/require.js"></script>
    <script src="require.config.js"></script>
    <script>
        require(["jquery", "registration"], function ($, registration) {
            $("body").append(registration.createForm({
                email: "[email protected]",
                password: "abc",
                password2: "abcd"
            }).$el);
        });
    </script>
    </body>
    </html>
    

    require config

    require.config({
        paths: {
            backbone: "lib/backbone",
            underscore: "lib/underscore",
            jquery: "lib/jquery-1.8.3.min",
            domReady: "lib/domReady",
            css: "lib/css",
            laconic: "lib/laconic",
            moment: "lib/moment.min",
            backboneUI: "lib/backbone-ui",
            backboneValidator: "../src/backbone-validator",
            backboneValidatorBasicTests: "../src/backbone-validator-basic-tests",
            backboneUIForm: "../src/backbone-ui-form",
            registration: "registration"
        },
        shim: {
            registration: {
                deps: [
                    "backboneUIForm",
                    "domReady!"
                ]
            },
            backboneValidator: {
                deps: ["backbone"]
            },
            backboneValidatorBasicTests: {
                deps: ["backboneValidator"]
            },
            backboneUIForm: {
                deps: ["backboneUI", "backboneValidator", "backboneValidatorBasicTests"]
            },
            backboneUI: {
                deps: ["backbone", "laconic", "moment", "css!lib/backbone-ui.css"],
                exports: "Backbone.UI"
            },
            laconic: {
                deps: ["jquery"],
                exports: "$.el"
            },
            backbone: {
                deps: ["underscore", "jquery"],
                exports: "Backbone"
            },
            underscore: {
                exports: "_"
            }
        }
    
    });
    
    opened by inf3rno 20
  • Shims not being shimmed within node.js

    Shims not being shimmed within node.js

    Consider the following files for a demonstration of code that works in the browser but fails in node:

    shim-module.js:

    console.log("Executing shim-module.js");
    var x = "Loaded OK";
    
    // Uncomment the following line to make this module act as an AMD module:
    //define([], x);
    

    index.js (node.js entry point):

    #!/usr/bin/env node
    
    var requirejs = require("requirejs");
    
    requirejs.config({
        shim: {
            "shim-module": { "exports": "x" }
        },
        nodeRequire: require
    });
    
    requirejs(["shim-module"], function (x) {
        console.log(x);
    });
    

    index.html:

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    var requirejs = {
        shim: {
            "shim-module": { exports: "x" }
        }
    };
    </script>
    <script src="node_modules/requirejs/require.js"></script>
    <script>
    require(["shim-module"], function (x) {
        console.log(x);
    });
    </script>
    </head>
    <body>
    </body>
    </html>
    

    The problem seems to be that a dependency marked as a shim in node is never the less loaded as if it were an AMD module. This is verifiable by rewriting the module as an AMD and observing that it then works.

    How to reproduce:

    1. Store the files in a folder and npm install requirejs.
    2. Open index.html in a web browser (I have been using Chrome) and inspect the log output. It says "Executing shim-module.js" and "Loaded OK".
    3. Run "./index.js" on the command line and observe the output.

    Expected: The node module should also output "Executing shim-module.js" and "Loaded OK".

    Observed: Instead, it outputs "Executing shim-module.js" and "undefined", indicating that nothing has been exported from the shim module, even though it was executed.

    opened by maghoff 20
  • order! plugin in chrome 6

    order! plugin in chrome 6

    Since the release of chrome 6, the order plugin seems to be slightly broken (only in that version of the browser).

    require() is sometimes (not easily reproducible) calling the "ready" function before all the code in the javascript files have been executed. Switching to recursive calls seems to fix the problem.

    For example... this doesn't work... // onready might be called before b.js is executed. require(["order!a.js", "order!b.js"], onready);

    But this does.

    // haven't seen a problem doing it this way... 
    require(["a.js"], function() {
        require(["b.js"], onready);
    });
    
    opened by amirshim 20
  • RequireJS is too big as a loader

    RequireJS is too big as a loader

    RequireJS is an amazing loader, but it is too big in many cases. Is there a plan to make a smaller version of requirejs by less features, only supports dynamic loading js, not supports plugins and low version browswers etc, like jQuery to Zepto?

    opened by lsycxyj 19
  • docs: Fix a few typos

    docs: Fix a few typos

    There are small typos in:

    • tests/jquery/scripts/jquery-1.7.1.js
    • tests/secondLateConfigPlugin/app/lib_/amd/nonamd.js

    Fixes:

    • Should read profiler rather than prefiler.
    • Should read corresponding rather than correposding.

    Semi-automated pull request generated by https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md

    opened by timgates42 0
  • Partial

    Partial "compilation"

    In my current setup I have my main project A that is consuming library B. Project A is being run through r.js and it generates bundles for library B along the process. Library B is getting quite big, and I'm thinking it's worth it to bundle (parts of perhaps) it as part of its build process.

    That would leave Project A consuming library B, alongside with a bundles config to know what's in B's bundle. Is it possible to do something like this currently? I would have to spend a few days trying to get this working if it's not really supported.

    opened by gsmeets 0
  • Allow for -.js in modules names.

    Allow for -.js in modules names.

    As per contribution guidelines I assume this fork is a one/two line fix.

    User story: In our project we use Chart.js which we defined in paths as "chartjs": "filepath". As You can see the module name is without the dot. But we also need chartjs-adapter-moment which assumes and requires module named 'chart.js'. Currently we forked the chartjs-adapter-moment and made needed change to allow working it with Require.js.

    Problem: Even if there's a 'chart.js' module defined in config.paths it won't work because Require.js assumes 'chart.js' is a file path because of the -.js.

    Solution: If there's module defined in config.paths with -.js inside then use the defined path instead first assuming that it's a js file path. Simply saying: just check first if exact name is defined in config.paths and if not then go with the old way. If my solution is not good enough please adjust it as You like, but don't ignore the -.js module name problem.

    opened by ThomasK0lasa 0
  • CLA replacement

    CLA replacement

    I see that this repo is still using the old CLA Assistant for CLA signatures. This infra no longer works. We've changed the infrastructure for OpenJS Foundation projects to use EasyCLA for the other former JSF projects. Would you like us to make this migration here?

    cc/ @jorydotcom

    opened by brianwarner 2
  • Unable to correctly parse path without resorting to calling `toUrl`

    Unable to correctly parse path without resorting to calling `toUrl`

    We are migrating from on prem to a SharePoint Online. We have a tenant-level URL where most of the shared scripts go. Under the root we have a bunch of nested sites.

    The baseUrl maps to the SiteAssets ascript found in at root. The ~ intends to permit you grab scripts for the subsite's own SiteAssets, not those shared at the root.

    requirejs.config({
      baseUrl: '/SiteAssets', // => https://myorg.sharepoint.com/SiteAssets
      bundles: {
        "forms": ['form', 'check', 'list'],
        "core": ['repo', 'request', 'web', 'lookups', 'pred', 'dates', 'format', 'memoized']
      },
      paths: {
        "~": `${_spPageContextInfo.webServerRelativeUrl}/SiteAssets`, // => https://myorg.sharepoint.com/sites/subsite/SiteAssets
        ...
        "text": "vendor/require/text",
        "css": "vendor/require/css",
        "promised": "vendor/require/promised"
      }, ...
    });
    

    The point of the tilde is to allow the subsite to refer up to the shared library of scripts at the root or at the local scripts.

    Unfortunately, the following require (nested hundreds of lines deep within a larger AMD module) will not resolve correctly. The final URL has the ~ embedded in the middle of it, like the outer and inner contexts got jammed together.

    require(['~/SiteAssets/components/month-pager/index.js'], function(monthPager){
      ...
    });
    

    But if I resort to the following shenanigan it resolves fine. Odd that the behavior of internal URL resolution is inconsistent with what is presented externally via toUrl.

    require([require.toUrl('~/SiteAssets/components/month-pager/index.js')], function(monthPager){
    
    });
    
    opened by mlanza 0
A Module Loader for the Web

A Module Loader for the Web Sea.js is a module loader for the web. It is designed to change the way that you organize JavaScript. With Sea.js, it is p

seajs 8.3k Jan 3, 2023
Dynamic ES module loader

SystemJS SystemJS is a hookable, standards-based module loader. It provides a workflow where code written for production workflows of native ES module

null 12.4k Dec 29, 2022
Asyncronous JavaScript loader and dependency manager

$script.js - Async JavaScript loader & dependency manager $script.js is an asynchronous JavaScript loader and dependency manager with an astonishingly

Dustin Diaz 2.9k Jan 3, 2023
:skull: An ancient tiny JS and CSS loader from the days before everyone had written one. Unmaintained.

LazyLoad Note: LazyLoad is no longer being maintained. I'm not responding to issues or pull requests, since I don't use this project anymore and don't

Ryan Grove 1.4k Jan 3, 2023
enterprise standard loader

ESL (Enterprise Standard Loader) ESL是一个浏览器端、符合AMD的标准加载器,适合用于现代Web浏览器端应用的入口与模块管理。 ESL is a browser-only, amd-compliant module loader. In modern web app

Baidu EFE team 833 Dec 16, 2022
Lightweight JavaScript module system.

modulejs Lightweight JavaScript module system. License The MIT License (MIT) Copyright (c) 2020 Lars Jung (https://larsjung.de) Permission is hereby g

Lars Jung 124 Dec 21, 2022
A file and module loader for JavaScript

RequireJS RequireJS loads plain JavaScript files as well as more defined modules. It is optimized for in-browser use, including in a Web Worker, but i

null 12.9k Dec 27, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Moxiecode 5.6k Jan 1, 2023
An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

Snyk Labs 57 Dec 28, 2022
curl.js is small, fast, extensible module loader that handles AMD, CommonJS Modules/1.1, CSS, HTML/text, and legacy scripts.

curl (cujoJS resource loader) All development for curl.js and cram.js has stopped. For the foreseeable future, we will continue to respond to issues o

The Javascript Architectural Toolkit 1.9k Dec 30, 2022
A Module Loader for the Web

A Module Loader for the Web Sea.js is a module loader for the web. It is designed to change the way that you organize JavaScript. With Sea.js, it is p

seajs 8.3k Jan 3, 2023
Dynamic ES module loader

SystemJS SystemJS is a hookable, standards-based module loader. It provides a workflow where code written for production workflows of native ES module

null 12.4k Dec 29, 2022
.properties file parser, JSON converter and Webpack loader.

properties-file .properties file parser, JSON converter and Webpack loader. Installation ?? ⚠ in June 2022 we have released version 2 of this package

Avansai 6 Dec 15, 2022
A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM deffiniation and appropriate file structure.

Welcome to function-stencil ?? A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM

Ben Smith 21 Jun 20, 2022
A basic USDZ file (Pixar Universal Scene Description) loader for ThreeJS

Three USDZ Loader A basic USDZ (binary Universal Scene Description) reader for Three.js The plugins supports animation as well as loading multiple USD

Pierre-Olivier NAHOUM 37 Dec 13, 2022
Serve file server with single zip file as file system in Deno.

zipland Serve file server with one-single zip file in Deno. Support zip just zip32 with deflated or uncompressed serving plaintext deflate Examples Yo

Yongwook Choi 18 Nov 2, 2022