This article mainly introduces the usage and difference between Javascript (es2016) import and require. It has certain reference value. If you are interested, you can learn more.
This article introduces the usage of Javascript (es2016) import and require. I would like to share with you the detailed explanation of the difference, as follows:
Write a simple js file, assuming the name is: lib.js. Assume that the content is as follows:
export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); }
In this way, the properties and methods defined in the lib can be referenced elsewhere. There are two reference methods, namely import and require.
//方法一 import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3)); //方法儿 import * as lib from 'lib'; square = lib.square;
You can also set the default export information, you need to define export default {} in lib.js. Default can be followed by a parameter or an array. The writing method is:
//------ module1.js ------ export default 123; //------ module2.js ------ const D = 123; export { D as default };
It is usually more customary to use the first method. Then use import to get this array or parameters. However, import can only be used for static import, which means it must be written at the top level at the beginning of the file. And require can achieve dynamic loading.
Loading method | Specification | Command | Features |
---|---|---|---|
Runtime loading | CommonJS/AMD | require | Community solution provides a server/browser module loading solution. Non-linguistic standards. Module dependencies and input/output variables can only be determined at runtime, and static optimization cannot be performed. |
Loaded during compilation | ESMAScript6+ | import | Supports module functions at the language specification level. Supports static analysis at compile time, which facilitates the introduction of macros and type checking into JS. Dynamic binding. |
##
const incrementCounter = function ({dispatch,state}){ dispatch(‘INCREMENT‘) } export default { incrementCounter } //require let myAction = require(‘xxxxx‘); myAction.default.incrementCounter()
The above is the detailed content of Compare the differences between import and require in Javascript. For more information, please follow other related articles on the PHP Chinese website!