Difference between require and import in JavaScript

When modifying vue&react and webpack, I often see require and jload in js file, both of which are used for JS modular programming (CSS is @import). Let's look at the difference between them. where.

The most important idea in node programming is modularity, and both import and require are used by modularity.

  • Follow the specification
    • 1.1 require is the introduction of the AMD specification
    • 1.2 import is a grammar standard for es6. If you want to be compatible with the browser, you must convert it to es5 syntax.
  • 2. Call time
    • 2.1 require is a runtime call, so require can theoretically be used anywhere in the code
    • 2.2 import is called at compile time, so it must be placed at the beginning of the file
  • 3. Nature
    • 3.1 require is the assignment process, in fact, the result of require is the object, number, string, function, etc., and then assign the result of require to a variable
    • 3.2 When the underlying data type is introduced via require, it is copied.
    • 3.3 When introducing a complex data type with require, the data is lightly copied to the object.
    • 3.4 When a circular reference between modules occurs, the executed module is output, and the unexecuted module is not output (more complicated)
    • 3.5 CommonJS module default export is an object, even if the basic data type is exported
    • 3.6 import is a destructuring process, but currently all engines have not implemented import, we use babel to support ES6 in node, just transcode ES6 to ES5 and execute, import syntax will be transcoded to require

Let's take a look at the features of running and compile-time loading.

Loading method specification command Characteristics
Runtime load CommonJS/AMD require A community scenario that provides a server/browser module loading scenario. Non-verbal level standards. Module dependencies and input/output variables can only be determined at runtime and cannot be statically optimized.
Load at compile time ESMAScript6+ import The language specification level supports module functions. Support compile-time static analysis, which is convenient for JS to introduce macro and type checking. Dynamic binding

Related knowledge points

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

Require is the syntax of CommonJS. The module of CommonJS is an object. When you input, you must find the object property.

let { stat, exists, readFile } = require('fs');

 // Equivalent to 
let _fs = require('fs');
let stat = _fs.stat;
let exists = _fs.exists;
let readfile = _fs.readfile;

About: The whole load fs module (that is, load all methods of fs), generate an object "_fs", and then read three methods from this object, this is called "runtime loading", because only the runtime can get this object, Cannot be static at compile time.

The ES6 module is not an object, but displays the specified output code via the export command and then imports it via import.

import { stat, exists, readFile } from 'fs';
above: Load "stat, exists, readFile" from fs three methods, other methods do not load,

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

Among the ES6 modules, the top of this points to undefined, ie this should not be used in the top-level code.
Module is mainly composed of two commands, import and export, export is used to specify the external interface of the module, and import command is used to input the functions provided by other modules.

3.Export

A module is a separate file, and all variables inside the file are not available externally. If you want to get a variable, you must output it via export.

// profile.js
export 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.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;

export {firstName, lastName, year};

In addition to output variables, you can also output functions or classes.

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

It can also be batch output, also included in braces, or renamed with as:

function v1() { ... }
function v2() { ... }

export {
  v1 as streamV1,
  v2 as streamV2,
  v2 as streamLatestVersion
};

Attention:
The export command specifies the external interface, which must establish a one-to-one correspondence with the internal variables of the module.

// write one
export var m = 1;

 // write two
var m = 1;
export {m};

 // write 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 is provided, the first type directly outputs 1, and the second type has a variable m, but still outputs 1 directly, which makes it impossible to deconstruct.
Similarly, the output of function and class must also follow this way of writing.

The interface output by the And:export statement is a dynamic binding relationship with its corresponding value, that is, the real-time values ​​of the module are obtained through the interface. The export module can be located anywhere in the module, but it must be at the top of the module, and if it is in another scope, an error will be reported.
function foo() {
  export default 'bar' // SyntaxError
}
foo()
4.Import command

After export defines the external interface of the module, other JS files can be loaded by import.

// main.js
import {firstName, lastName, year} from './profile';

function setName(element) {
  element.textContent = firstName + ' ' + lastName;
}

The import command accepts a pair of curly braces that specify the name of the variable to be imported from other modules. It must be the same name as the external interface of the imported module (profile.js).
If you want to re-add a name to the imported variable, you can use the as keyword.

import { lastName as surname } from './profile';

The from after import can specify the path name of the module to be imported. It can be an absolute path or a relative path. The .js path can be omitted. If there is only a module name and no path, a configuration file is required.
Note that the import command has a boost effect and will be promoted to the head of the entire module, first executed. (is executed during the compilation phase)
Because import is statically executed, you can't use expressions and variables, that is, the syntax structure of the result at runtime (e.g. if...else...)

5.module's overall loading

In addition to specifying an output value to be loaded, you can also specify an object with (*), and all variables will be loaded on this 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 is loaded in a module

import { area, circumference } from './circle';

 Console.log('circle area: ' + area(4));
 Console.log('circle length: ' + circumference(14));

 / / The above is to specify the method to be loaded one by one, the overall loading is written as follows.
import * as circle from './circle';

 Console.log('circle area: ' + circle.area(4));
 Console.log('circle length: ' + circle.circumference(14));

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

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 with import, you need to know the variable name or function name to be loaded in the module. The user may not want to read the source code. Just use the interface directly, you can use the export default command to specify the output for the module.

// export-default.js
export default function () {
console.log('foo');
}
When other modules load the module, the import command can assign an arbitrary name to the anonymous function.

// import-default.js
import customName from './export-default';
customName(); // 'foo'
export default can also be used before non-anonymous functions.

6.export default

In the previous example, when importing with import, you need to know the variable name or function name to be loaded in the module. The user may not want to read the source code. Just use the interface directly, you can use the export default command to specify the output for the module.

// export-default.js
export default function () {
  console.log('foo');
}

When other modules load the module, the import command can assign an arbitrary name to the anonymous function.

// import-default.js
import customName from './export-default';
customName(); // 'foo'

Export default can also be used before non-anonymous functions.
Let's compare the default output with the normal output.

// First group 
 Export default function crc32() { // output
  // ...
}

 Import crc32 from 'crc32'; // enter

 // Second Group 
 Export function crc32() { // output
  // ...
};

 Import {crc32} from 'crc32'; // enter

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

The import and export commands can only be at the top level of the module and cannot be in the code block. Otherwise the syntax will be incorrect.
This design can improve compiler efficiency, but there is no way to implement runtime loading.
Because require is a runtime load, the import command has no way to replace the dynamic loading of require.
So introduced the import() function. Complete dynamic loading.
import(specifier)
The specifier is used to specify the location of the module to be loaded. What parameters can be accepted by import, 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 occasions
  • 1) Load on demand:
    button.addEventListener('click', event => {
      import('./dialogBox.js')
      .then(dialogBox => {
        dialogBox.open();
      })
      .catch(error => {
        /* Error handling */
      })
    });
    
    above: The import module is in the event listener function, which will only be loaded if the user clicks the button.
  • 2) Conditional loading:
    import() can be placed in an if...else statement to implement conditional loading.
    if (condition) {
      import('moduleA').then(...);
    } else {
      import('moduleB').then(...);
    }
    

Intelligent Recommendation

Analysis of the difference between import and require

1. require is the AMD specification, and import is the ES6 module. 2. require similar way of writing It seems to only introduce a, b, c, actually introduce the whole module, and then assign the corres...

[js] difference between require and import

Article directory The difference between `require` and `import` origin Export command / import command CommonJS es6 Static optimization requirewithimportDifference origin Before the birth of es6, js h...

The difference between require and import in vue

The difference between require and import Before es6, js has not had its own module syntax. In order to solve this problem, there is a requirement for require.js. After the release of es6, js introduc...

The difference between the import and require the webpack

Foreword Some time ago wrote an articleimport and require Depth - depth from shallow thinking to bring NodeThe articles comeimportis based onrequireImplementation, and implementation is different in d...

(Transfer) The difference between import and require

Before ES6, there was a bill to load JS modules, the most important being CommonJS and AMD specifications. The former CommonJS is mainly used in servers to achieve synchronous loading, such as nodejs....

More Recommendation

The difference between modular require and import

When the front-end application becomes more and more complex, we want to divide the code into different modules for easy reuse and on-demand loading. Require and import are statements that introduce m...

The difference between the Require and Import of Vue

First we have to understand the basic syntax of Require and Import: REQUIRE's basic syntax: Define module.export in the exported file, the type of object to export is not limited (which can be any typ...

The difference between import module require and import in node

Should I use require or import? The use of require is very simple, it is equivalent to the portal of module.exports, what is behind module.exports, what is the result of require, objects, numbers, str...

Javascript (es2016) import and require usage and difference

Write a simple js file, assuming the name is: lib.js . The assumptions are as follows: This way you can reference the properties and methods defined in lib in other places. There are two ways to refer...

What is the difference between js using require and import?

Both require and import are used for js modularization. First, require Require is the specification of commonjs. The node application is composed of modules and complies with the specification of comm...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top