Require js how does it work




















RequireJS is a well known JavaScript module and file loader which is supported in the latest versions of popular browsers. In RequireJS we separate code into modules which each handle a single responsibility. Additionally, dependencies need to be configured when loading files. Once downloaded, copy the file to your project folder. The file main. This is the only code required to include files using RequireJS.

You might be wondering what happened to the other files and how they are included. The data-main attribute defines the initialization point of the application. In this case, it is main. RequireJS uses main. In this scenario all the files are located in same folder. Using logic, you can move the files to any folder you prefer. In RequireJS, all code is wrapped in require or define functions. The first parameter of these functions specifies dependencies.

In the previous example, initialization is dependent on purchase. Note that the file extension has been omitted. This is because RequireJS only considers. The second parameter to require is an anonymous function which takes an object that is used to call the functions inside the dependent file.

In this scenario, we have just one dependency. Multiple dependencies can be loaded using the following syntax. In this section we are going to convert the plain JavaScript example discussed in the previous section into RequireJS.

We already covered main. First, we declare that purchase functionality depends on credits and products. Inside the return statement, we can define the functions of each module. Here, we have called the getCredits and reserveProduct functions on the objects passed. Both of these files are configured as independent modules — meaning they are not dependent on anything. You probably have a console write stuff in your code, so that when debugging and tracing it works wonders.

It will increase file size and slow down execution. It may even cause your script to throw an error cough, IE8. You have an opportunity to sanitize your code from that console stuff. Here is how you do it:. There is another hook onBuildWrite , which will be called for each module before writing contents to disk.

This might be useful if you want to include copyrights or any other additional text. This will result into two http requests. This is not going to fly for performance obsessed people. This will include RequireJS into output. Make sure to load it asynchronously so that it does not block rendering. Even if you are not doing this you can load initial RequireJS asynchronously too:. As web developers , we often need to load resources other than just javascript.

Here is where RequireJS plugins are very useful. Plugin is just another module that implements a specific API. The plugin name and module name are separated by!. A comprehensive list of plugins is listed in RequireJS Wiki. There are cases when you may need to load or work with libraries that do not use define. For that you can use shim configuration:. It is important in this case to understand dependencies well. In this case, you may need to expose it manually before loading the library that it is dependent on in the presence of that global variable.

If you are an author of a library or jQuery plugin, be kind and expose your library as a plugin. Or, optionally specify dependencies so that someone using AMD can use it as a module. This way it can be included as a simple script or referenced as a dependency. If your library has any dependencies, for example jQuery plugin, you may chose to use the following pattern:. As you can see, we are immediately invoking an anonymous function and as a parameter inlining function which has all the logic inside.

This way if define is present, we are not doing anything, just defining a module, otherwise invoking it immediately by passing dependencies in this case jQuery from the global scope.

Continuous Integration in. Normally you should not need to use require to fetch a module, but instead rely on the module being passed in to the function as an argument. Circular dependencies are rare, and usually a sign that you might want to rethink the design. However, sometimes they are needed, and in that case, use require as specified above. If you are familiar with CommonJS modules, you could instead use exports to create an empty object for the module that is available immediately for reference by other modules.

By doing this on both sides of a circular dependency, you can then safely hold on to the the other module. This only works if each module is exporting an object for the module value, not a function:. Or, if you are using the dependency array approach, ask for the special 'exports' dependency:. If the JSONP service times out, it means other modules you define via define may not get executed, so the error handling is not robust. Errors in loading a JSONP service are normally surfaced via timeouts for the service, since script tag loading does not give much detail into network problems.

To detect errors, you can override requirejs. There is more information in the Handling Errors section. There is a global function, requirejs.

It will reset the loader's internal state to forget about the previous definition of the module. However , it will not remove the module from other modules that are already defined and got a handle on that module as a dependency when they executed. So it is really only useful to use in error situations when no other modules have gotten a handle on a module value, or as part of any future module loading that may use that module.

See the errback section for an example. If you want to do more sophisticated dependency graph analysis for undefining work, the semi-private onResourceLoad API may be helpful. RequireJS waits for all dependencies to load, figures out the right order in which to call the functions that define the modules, then calls the module definition functions once the dependencies for those functions have been called.

Note that the dependencies for a given module definition function could be called in any order, due to their sub-dependency relationships and network load order. Using RequireJS in a server-side JavaScript environment that has synchronous loading should be as easy as redefining require. The build system does this, the require.

When using require in the top-level HTML page or top-level script file that does not define a module , a configuration object can be passed as the first option:. You may also call require. Avoid other entry point scripts which wrongly assume that data-main and its require. Also, you can define the config object as the global variable require before require.

This example specifies some dependencies to load as soon as require. There are some patterns for separating the config from main module loading. If no baseUrl is explicitly set in the configuration, the default value will be the location of the HTML page that loads require. If a data-main attribute is used, that path will become the baseUrl. The baseUrl can be a URL on a different domain as the page that will load require.

RequireJS script loading works across domains. The only restriction is on text content loaded by text! The optimization tool will inline text!

The path that is used for a module name should not include an extension, since the path mapping could be for a directory. The path mapping code will automatically add the. If require. When run in a browser, paths fallbacks can be specified, to allow trying a load from a CDN location, but falling back to a local location if the CDN location fails to load. That config states: modules 'main', 'util', 'text' and 'text!

Module 'text! This only sets up where to find a module inside a script that has multiple define 'd modules in it. It does not automatically bind those modules to the bundle's module ID. The bundle's module ID is just used for locating the set of modules. Something similar is possible with paths config, but it is much wordier, and the paths config route does not allow loader plugin resource IDs in its configuration, since the paths config values are path segments, not IDs.

Note that the keys and values are module IDs , not path segments. They are absolute module IDs, not a module ID prefix like paths config or map config. Also, bundle config is different from map config in that map config is a one-to-one module ID relationship, where bundle config is for pointing multiple module IDs to a bundle's module ID.

As of RequireJS 2. See the bundlesConfigOutFile build config option for more details. Here is an example. It requires RequireJS 2. If not, then you may need to set a paths config for them:. In RequireJS 2. In that case, it functioned the same as the "init" property as shown above. The "init" pattern is used in RequireJS 2. For "modules" that are just jQuery or Backbone plugins that do not need to export any module value, the shim config can just be an array of dependencies:.

Note however if you want to get load detection in IE so that you can use paths fallbacks or errbacks, then a string exports value should be given so the loader can check if the scripts actually loaded a return from init is not used for enforceDefine checking :. This sort of capability is really important for larger projects which may have two sets of modules that need to use two different versions of 'foo', but they still need to cooperate with each other.

This is not possible with the context-backed multiversion support. In addition, the paths config is only for setting up root paths for module IDs, not for mapping one module ID to another one. This feature only works well for scripts that are real AMD modules that call define and register as anonymous modules.

Also, only use absolute module IDs for map config. Relative IDs like '.. If there is a more specific map config, that one will take precedence over the star config. Note: when doing builds with map config, the map config needs to be fed to the optimizer, and the build output must still contain a requirejs config call that sets up the map config. The optimizer does not do ID renaming during the build, because some dependency references in a project could depend on runtime variable state.

So the optimizer does not invalidate the need for a map config after the build. That configuration info is usually known as part of the application, and there needs to be a way to pass that down to a module. In RequireJS, that is done with the config option for requirejs. Modules can then read that info by asking for the special dependency "module" and calling module. For passing config to a package , target the main module in the package, not the package ID:. See the packages topic for more information.

If you end up using modules installed from npm, then you may need to set this config value to true to avoid resolution issues. This option only applies to treating the ". Available in 2. Setting it to 0 disables the timeout.

The default is 7 seconds. This allows require. To use it correctly, see the Multiversion Support section. Useful when require is defined as a config object before require. Using deps is just like doing a require [] call, but done as soon as the loader has processed the configuration. It does not block any other require calls from starting their requests for modules, it is just a way to specify some modules to load asynchronously as part of a config block.

See Catching load failures in IE for more information. Most useful to cache bust when the browser or server is not configured correctly. Example cache bust setting for urlArgs:. Return an empty string if no args. Be sure to take care of adding the '?

During development it can be useful to use this, however be sure to remove it before deploying your code. To use Firefox's JavaScript 1.



0コメント

  • 1000 / 1000