Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Aug 8, 2019. It is now read-only.
/docsPublic archive
yyh321 edited this pageOct 10, 2016 ·18 revisions

The CommonJS group defined a module format to solveJavaScript scope issues by making sure each moduleis executed in its own namespace.

This is achieved by forcing modules to explicitly exportthose variables it wants to expose to the "universe",and also by defining those other modules required toproperly work.

To achieve this CommonJS gives you two tools:

  1. therequire() function, which allows to import a given module into the current scope.
  2. themodule object, which allows you to export something from the current scope.

The mandatory hello world example:

Plain Simple JavaScript

Here is an example without CommonJS:

We will define a value in a script file namedsalute.js.This script will contain just a value that will be used in other scripts:

// salute.jsvarMySalute="Hello";

Now, in a second file namedworld.js, we aregoing to use the value defined insalute.js.

// world.jsvarResult=MySalute+" world!";

Module definitions

As it is,world.js will not work asMySalute is not defined.We need to define each script as a module:

// salute.jsvarMySalute="Hello";module.exports=MySalute;
// world.jsvarResult=MySalute+"hello world!";module.exports=Result;

Here we make use of the special objectmodule and place a reference of ourvariable intomodule.exports so the CommonJS module system knows this isthe object of our module we want to show to the world.salute.js disclosesMySalute, andworld.js disclosesResult.

Module dependency

We're near but there's still a step missing: dependency definition.We've already defined every script as an independent module, butworld.jsstill needs to know who definesMySalute:

// salute.jsvarMySalute="Hello";module.exports=MySalute;
// world.jsvarMySalute=require("./salute");varResult=MySalute+"world!";module.exports=Result;

Note that we didn't use the full filenamesalute.js but./salute when callingrequire, so you can omit the extension of your scripts../ means that thesalute module is in the same directory as theworld module.

Examples

Functions

// moduleA.jsmodule.exports=function(value){returnvalue*2;}
// moduleB.jsvarmultiplyBy2=require('./moduleA');varresult=multiplyBy2(4);

webpack 👍

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp