The difference between require and import in JS

Source: Internet
Author: User
Tags crc32 event listener readfile

In the study of react and webpack, often see in the JS file appears require, there are import, these two are for JS modular programming use. The CSS is@import

The design idea of the 1.ES6 module is to make it as static as possible, so that the dependencies of the module can be determined at compile time, as well as the input and output variables.

Require is the COMMONJS syntax, COMMONJS's module is an object, and you must find the object property when you enter it.

COMMONJS module Let {stat, exists, readFile} = require (' FS ');//equivalent to let _fs = require (' FS '); let stat = _fs.stat;let exists = _fs.exists;let ReadFile = _fs.readfile;

Above: Load FS module as a whole (that is, load fs all methods), generate an Object "_fs", and then read three methods from this object, this is called "Runtime Load", because only the runtime can get this object, not at compile time to do static.

Instead of an object, the ES6 module displays the specified output code through the Export command, and then imports it through the import.

Import {stat, exists, readFile} from ' FS ';

Above: Load from FS "stat, exists, readFile" Three methods, other methods do not load,

The 2.ES6 module uses strict mode by default, regardless of whether "use strict" is declared

ES6 module, the top level of this the point undefined , that should not be used in the top-level code this .

module is composed of two commands, import and export,export are used to specify the external interface of the module, the import command is used to enter the functions provided by other modules.

3.Export

The module is a stand-alone file that cannot be retrieved from any external variables inside the file. If you want to get a variable, you must pass the export output,

profile.jsexport var firstName = ' Michael '; export var lastName = ' Jackson '; export var year = 1958;

Or in a better way: Use curly braces to specify a set of variables to output

Profile.jsvar firstName = ' Michael '; var lastName = ' Jackson '; var year = 1958;export {firstName, lastName, year};

In addition to output variables, you can also output functions or classes (Class),

Export function multiply (x, y) {  return x * y;};

You can also batch output, which is also included in curly braces or as a rename:

Function v1 () {...} Function v2 () {...} Export {  v1 as streamV1,  v2 as streamV2,  v2 as streamlatestversion};

Attention:

The Export command specifies an external interface, which must be established with a one by one corresponding relationship to the module internal variables.

Writing an export var m = 1;//notation two var m = 1;export {m};//notation three var n = 1;export {n as m};//error export 1;//error var m = 1;export m;

The reason for the error is: No external interface, the first direct output 1, the second, although there is a variable m, but still direct output 1, resulting in the inability to deconstruct.

The same, function and class the output, must abide by such a notation.

Error function f () {}export f;//correct export function f () {};//correct function f () {}export {f};

The interface to the output of the And:export statement is a dynamically bound relationship with its corresponding value, that is, the real-time value inside the module that is taken through the interface.

Location: The export module can be located anywhere in the module, but must be at the top level of the module and will be an error if in other scopes.

function foo () {  export default ' bar '//Syntaxerror}foo ()

4.Import command

Export defines the external interface of the module, other JS files can be loaded by import to the module,

Main.jsimport {firstName, lastName, year} from './profile '; function setName (Element) {  element.textcontent = FirstName + "+ lastName;}

The import command accepts a pair of curly braces, which specifies the name of the variable to be imported from the other module, and must be the profile.js same as the external interface of the imported module () .

If you want to re-give the imported variable a name, you can use the AS keyword,

Import {LastName as surname} from './profile ';

After import, the from can specify the path name of the module to be imported, either an absolute or a relative path, and the. js path can be omitted if only the module name, without the path, requires a configuration file designation.

Note that the import command has an elevation effect , which is lifted to the head of the entire module and executed first. (performed during the compile phase)

Because import is executed statically, you cannot use expressions and variables, that is, to get the syntax structure of the result at run time (e.g. If...else ... )

5.module of the overall load

In addition to specifying that an output value be loaded, you can specify an object with (*), and all of the variables will be loaded on the object.

Circle.js. Output two functions Export function area (RADIUS) {  return Math.PI * radius * RADIUS;} Export function circumference (RADIUS) {  return 2 * math.pi * RADIUS;} Main.js loaded in a module import {area, circumference} from './circle '; Console.log (' Circle Size: ' + areas (4)); Console.log (' circumference length: ' + CIRCUMF Erence (14));//The above is written to specify the method to be loaded, the overall load is as follows. Import * as Circle from './circle '; Console.log (' Circle area: ' + Circle.area (4)) Console.log (' circumference length: ' + circle.circumference (14) ');

Note that the object in which the module is loaded as a whole (the example above circle ) should be statically parsed , so the runtime is not allowed to change.

Import * as Circle from './circle ';//The following two lines are not allowed Circle.foo = ' hello '; circle.area = function () {};

6.export Default

In the previous example, when importing using import, you need to know the name of the variable or function to be loaded in the module, the user may not want to read the source code, just want to use the interface directly, you can use the Export default command, the module to specify the output

Export-default.jsexport default function () {  console.log (' foo ');}

When other modules load the module, the import command can specify any name for the anonymous function.

Import-default.jsimport customname from './export-default '; Customname (); ' Foo '

Export default can also be used before non-anonymous functions.

The default output and normal output are compared below.

First group export default function Crc32 () {//output  //...} Import CRC32 from ' CRC32 '; Input//second group export function Crc32 () {//output  //...}; Import {CRC32} from ' CRC32 '; Input

As you can see, when using export default, the import statement does not use curly braces.

importand export commands can only be on the top level of the module, not within the code block. Otherwise there will be a syntax error.

Such a design can improve compiler efficiency, but there is no way to implement runtime loading.

Because require is run-time loaded, the import command has no way to replace the Require dynamic load feature.

So the import () function is introduced. completes the dynamic load.

Import (specifier)

The specifier is used to specify the location of the module to be loaded. Import can accept the parameters, import () can accept the same parameters.

Import () returns a Promise object.

Const MAIN = document.queryselector (' main '); Import ('./section-modules/${somevariable}.js ')  . Then (module = =    Module.loadpageinto (main);  })  . catch (Err = {    main.textcontent = err.message;  });

7.import () function for Applications

1) Load on demand:

Button.addeventlistener (' click ', event = = {  import ('./dialogbox.js ')  . Then (DialogBox =    Dialogbox.open ();  })  . catch (Error =/    * ERROR handling */  })});

Above:import module in the event listener function, only the user clicks the button, the module will be loaded.

2) Conditional loading:

Import () can be placed in the If...else statement to implement conditional loading.

if (condition) {  import (' Modulea '). then (...);} else {  import (' Moduleb '). then (...);

The---is excerpted from Nandashin's ES6 and is for your own records only.

The difference between require and import in JS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.