The basic concept

The js file is read and executed by require, and the module exports object is returned. Node uses the CommonJS module specification. Modules are loaded synchronously according to the CommonJS specification. Subsequent operations can be performed only after the loading is complete.

Import a function, object, or basic type used to import external modules, other scripts, etc. Import is an ES6 command. Unlike require, it generates a reference to an external module instead of loading the module, and loads the values in the module only when the module is actually used.

Static and dynamic compilation

Requir is compiled dynamically

The first time a module is loaded, Node caches it, and subsequent loads retrieve it from the cache.

Require is called at runtime, so require could theoretically be used anywhere in the code.

//example.js
module.exports = {
    say: 'hi'
}

//main.js
require('./example').say = 'hello'
const test = require('./example').say
console.log(test)       //hello
Copy the code

The test above reintroduces example, but its say attribute is the same as hello, indicating that the example module was not reloaded, but was retrieved from the cache, so the say attribute is not hi

Import static compilation

ES6 module compilation: When you import a module, you only generate references and then value them when needed, so there is no caching problem, and variables in a module are bound to the module where they are.

Import is called at compile time. Although the import command has the effect of being promoted to the head of the entire module, it is recommended to place it at the beginning of the file.

// base.js
export var foo = 'bar';
setTimeout((a)= > foo = 'baz change'.500);

// main.js
import { foo } from './base';
console.log(foo); // bar
setTimeout((a)= > console.log(foo), 600);// baz changed
Copy the code

As you can see from the above code, the values of foo retrieved are different because import is loaded dynamically and you are aware of changes in base.js.

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

Because require is loaded at run time, the import command has no way to replace the dynamic loading functionality of require.

Import To implement dynamic loading, the import() function is introduced, which returns a promise object.


import(`./xxxx.js`)
  .then(module= >{... }) .catch(err= >{... });Copy the code

However, there is a problem with this: the module may be called before it is fully loaded, and the call will fail.

// base.js
export var fish;

setTimeout((a)= > fish = 'fish'.500);


// main.js
import { fish } from './base';

console.log(fish); //undefined
Copy the code

Babel transcoding for import

Because current browsers do not fully support import, we need to transcode import to require via Babel.

// es6Test.js
import * as actions from './searchAccount.actions';
import kdbTheme from '.. /.. /.. /common/Dialog/panguTheme.css';
import { createCommonAccount } from './createDialog.actions';

console.log('createCommonAccount###', createCommonAccount);
// Babel to compile es6test.js
/* import * as actions from './searchAccount.actions' */
var _searchAccount = require('./searchAccount.actions'); 

var actions = _interopRequireWildcard(_searchAccount);

/* import kdbTheme from '.. /.. /.. /common/Dialog/panguTheme.css' */
var _panguTheme = require('.. /.. /.. /common/Dialog/panguTheme.css');

var _panguTheme2 = _interopRequireDefault(_panguTheme);

/* import { createCommonAccount } from './createDialog.actions'*/
var _createDialog = require('./createDialog.actions');

console.log('createCommonAccount###', _createDialog.createCommonAccount);

function _interopRequireWildcard(obj) { 
    if (obj && obj.__esModule) { return obj; } 
    else {
        var newObj = {}; 
        if(obj ! =null) { 
            for (var key in obj) { 
                if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; 
            } 
        } 
        newObj.default = obj; 
        returnnewObj; }}function _interopRequireDefault(obj) { 
    return obj && obj.__esModule ? obj : { default: obj }; 
}
Copy the code

About the use of both

require

  1. Require: function, used to import modules

  2. Module. exports: a variable used to export modules

module.exports = ...

exports.xxx = ...

const xxx = require('/xxx')
const {xxx1, xxx2, xxx3} = require('/xxx')

Copy the code

import

  1. Import: import

  2. Export: export

import xxx from '/xxx'

import * as xxx from '/xxx'

import {xxx1, xxx2, xxx3} from '/xxx'

export xxx

export {xxx1, xxx2, xxx3}

export default xxx
Copy the code