Export and import for modularity
Read Catalogue
- ES6 the basic rules or characteristics of a module:
- The basic syntax for several import and export is listed below:
- ES6 imported modules are referred to as:
- Problems with cyclic dependencies:
- Browser compatible:
- Reference:
Before ES6, the front end was modular with Requirejs or SEAJS, and Requirejs was a modular library based on the AMD specification, while SEAJS was a modular library based on the CMD specification, both of which were designed to promote the front-end modular tools, and more about the difference between AMD and CMD , followed by a few links to the reference;
Now ES6 with the modular, is also the first JS support module, in a long time, we can directly function import and Export in the browser imported and exported each module, a JS file represents a JS module;
Modern browser to module support degree is different, currently are using Babeljs, or traceur ES6 code into a compatible ES5 version of the JS code;
Back to top ES6 's modular basic Rules or features:
ES6 the basic rules or characteristics of modularity, welcome to add:
1: Each module is loaded only once, each JS is executed only once, if the next time to load the same directory under the same file, read directly from memory. A module is a single case, or an object;
2: Variables declared within each module are local variables and do not pollute global scopes;
3: Variables or functions inside the module can be exported through export;
4: One module can import other modules
Run the following code
lib.js//Exporting Constants Export Const SQRT = math.sqrt;//Export function Square (x) { return x * x;} Export function diag (x, y) { return sqrt (square (x) + square (y));} Main.jsimport {square, diag} from './lib '; Console.log (square (11)); 121console.log (Diag (4, 3)); 5
Go back to the top list of several
ImportAnd
ExportThe basic syntax:
The first way to export:
In the Lib.js file, the interface is exported using the export{interface , and the interface name in the braces is the variable defined above, and the import and export are corresponding;
Run the following code
Lib.js file Let bar = "Stringbar", let foo = "Stringfoo", let Fn0 = function () { console.log ("Fn0");}; Let fn1 = function () { console.log ("fn1");}; export{Bar, foo, fn0, fn1}//main.js file import {bar,foo, fn0, fn1} from "./lib"; Console.log (bar+ "_" +foo); Fn0 (); fn1 ();
The second way to export:
In the export interface, we can use XX as YY, the name of the exported interface changed, such as: Closurefn as SAYINGFN, these interface names are changed to not read the document will know what to do:
Run the following code
Lib.js file Let Fn0 = function () { console.log ("Fn0");}; Let Obj0 = {}export {fn0 as foo, obj0 as bar};//main.js file import {foo, bar} from "./lib"; foo (); Console.log (bar);
The third way to export:
This is the way to define the exported function, or variable, directly in the export area:
Run the following code
Lib.js file export Let Foo = () = {Console.log ("Fnfoo"), return "foo"},bar = "Stringbar";//main.js file import {foo, bar} fro M "./lib"; Console.log (foo ()); Console.log (bar);
The fourth type of export:
This way of exporting does not need to know the name of the variable, the equivalent is anonymous, directly to the development of the interface to export;
If a JS module file has only one function, then you can use export default exports;
Run the following code
Lib.jsexport default "string";//main.jsimport defaultstring from "./lib"; Console.log (defaultstring);
The fifth method of export:
Export can also be exported by default function, when the import, the name casually write, because each module's default interface is one:
Run the following code
LIB.JSLET fn = () = "string"; export {fn as Default};//main.jsimport defaultfn from "./lib"; Console.log (DEFAULTFN ()) ;
The sixth method of export:
Use the wildcard *, re-export the interface of other modules (in fact, reproduced articles, and then do not specify the source);
Run the following code
Lib.jsexport * from "./other";//If you only want to export some interfaces, simply list the interface name//export {Foo,fnfoo} from "./other";//other.jsexport let foo = "s Tringfoo ", Fnfoo = function () {Console.log (" Fnfoo ")};//main.jsimport {foo, fnfoo} from"./lib "; Console.log (foo); Console.log (Fnfoo ());
Other: Import and export of ES6 provide quite a lot of importing and exporting syntax;
You can import external modules using the wildcard character * when importing:
Run the following code
Import * as obj from "./lib"; Console.log (obj);
Back to top ES6 the imported modules are all references:
Each imported JS module is live, each access to the module's variables or functions are up-to-date, this is the original ES6 module and AMD and CMD One of the differences, the following code modified from http:// Exploringjs.com/es6/ch_modules.html#_imports-are-read-only-views-on-exports
Run the following code
Lib.jsexport Let counter = 3;export function Inccounter () { counter++;} Export function Setcounter (value) { counter = value;} Main.jsimport {counter, inccounter, setcounter} from './lib ';//The Imported value ' counter ' is liveconsole.log (counter ); 3incCounter (); Console.log (counter); 4setCounter (0); Console.log (counter); 0
In Main.js, counter always points to the local variable counter in Lib.js, according to the urine of JS, like the number or string type or boolean value of the original value to be copied, not to be assigned;
Back to the top of the loop dependency problem:
The cyclic dependence of Nodejs is so handled: open;
Cyclic dependence is the problem of JS Modularization, in the browser side, using Requirejs test modularity, such as a file file0.js relies on file1.js, and File1.js relies on file0.js, So who is file0.js and file1.js to execute first?
Run the following code
index.html<! DOCTYPE html>
In the console, output is:
Run the following code
Undefinedobject {file1: "File1"} Object {file0: "FILE0"}
In the execution of file1.js time file0.js not finished, so output undefined, this output and Nodejs output is the same situation;
Then I used the Sits mass-framework Framework to try, Sits's framework directly prompted me: "the module and some of the previous modules have cyclic dependence", so it is better, Requirejs for the cycle of dependence is the direct implementation of the loop-dependent module, will lead to the development of the time to dig their own pits .... ;
Then I tested it under babel-node : Here are a few tests that can be ignored:
I use the ES6 module to try, as long as each module is referenced, regardless of whether the module is executed, the export of the module has been exported, if the export is a function:
Run the following code
Cyclic.jsimport fn0 from "./file0"; Fn0 (),//file0.jsimport fn1 from "./file1"; fn1 (); Console.log ("File0.js runs"); Export default function () {Console.log ("FILE0 export runs")}//file1.jsimport fn0 from "./file0"; Fn0 (); Console.log (" File1.js runs "), export default function () {Console.log (" File1 export Runs ")}
If you are exporting a string:
Run the following code
Cyclic.jsimport str from "./file0"; Console.log (str),//file0.jsimport str1 from "./file1"; Console.log (STR1) Console.log ("File0.js runs"); export default "STR0";//file1.jsimport str0 from "./file0"; Console.log (STR0) Console.log ("File1.js runs"); export default "str1";
If you are exporting an object:
Then the first line output an initial value {}, after the last wait for file0.js and file1.js execution finished, output file0.js exported objects;
If it is an array:
Then the first line outputs a statically parsed initial value undefined, and after the last wait for file0.js and file1.js to finish, the output file0.js the exported object;
If it is a Boolean value:
Then the first line outputs a statically parsed initial value undefined, and after the last wait for file0.js and file1.js to finish, the output file0.js The exported Boolean value;
Why is that? I seem to have found the answer here: Http://exploringjs.com/es6/ch_modules.html#_modules, ES6 's import and export were advanced to the top of JS, in functions or objects, Or the base value is exported in advance by static analysis, reference: http://www.ecma-international.org/ecma-262/6.0/#sec-parsemodule,/http www.ecma-international.org/ecma-262/6.0/#sec-toplevelmoduleevaluationjob
Conclusion: When exporting data interface with export of ES6, it is best to use functions uniformly to avoid cyclic dependence, because JS will parse different types of objects statically into different initial values;
1
1
Back to top browser compatible:Chrome browser currently does not support import, and export;
Firefox's support is also limited, better than chrome;
I use Babel;
Go back to the top of the reference:ecma-262:http://www.ecma-international.org/ecma-262/6.0/#sec-imports
Import:https://developer.mozilla.org/en-us/docs/web/javascript/reference/statements/import
Export:https://developer.mozilla.org/en-us/docs/web/javascript/reference/statements/export
babeljs:http://babeljs.io/
Exploring ES6 (Dr.axel rauschmayer): http://exploringjs.com/es6/ch_modules.html
Similarities and differences of SEAJS and Requirejs: https://github.com/seajs/seajs/issues/277
The biggest difference between Seajs and Requirejs: https://www.douban.com/note/283566440/
Mr. Ruan es6#module:http://es6.ruanyifeng.com/#docs/module
What are the differences between AMD and CMD: https://www.zhihu.com/question/20351507/answer/14859415
Export and import for modularity