Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Require and import are often used in the daily development process as modules are introduced. Usually in a project, we don’t have to deal with them and use them directly. But what’s the difference between the two? Let’s look at it today with a code…

require/exports

// module.js let counts = 1; function sayHello() { alert(`"hello , ${counts}`) } setTimeout(() => { counts += 2 }, 3000); module.exports = {counts, sayHello}; index.js const { counts, sayHello } = require('./module.js'); Const click = () => {console.log('counts: ', counts) // Importing counts is always 1 sayHello(); // 1 == "3 seconds later =>> 3}... <! <p>import {counts}</p> <Button type="primary" onClick={click}>require </Button>Copy the code

Change the value of the variable in the source file. Import counts by require. The value will always be the initial value

import/export

// module.js
    let counts = 1;
        function sayHello() {
        alert(`"hello , ${counts}`)
    }
    setTimeout(() => {
        counts += 2
    }, 3000);
    export { counts, sayHello };

    // index.js
    import { counts, sayHello } from './module.js';
    
    // 注意此处的代码结果
    const click = () => {
        console.log('counts: ', counts) // 初始为 1, ==》 3秒钟后 =>> 3
        sayHello(); // 初始为 1, ==》 3秒钟后 =>> 3
    }

    ...
    <!-- 此counts处始终是 1 -->
    <p>import {counts}</p> 
    <Button type="primary" onClick={click}>require </Button>
Copy the code

Import counts. After changing the values in the source file, the values will change as well.

The difference between require and import

  1. The importrequireexportexports/module.exportsCommonJSIs usually applicable to areas such asNode.js
  2. import/exportES6Is usually applicable to areas such asReact
  3. requireIs the assignment process and is executed at run time, i.e. asynchronous loading.
  4. requireIt can be understood as a global method, because it is a method which means it can be executed anywhere.
  5. importIs the deconstruction process and is executed at compile time.
  6. importMust be written at the top of the file.

Commonjs prints a copy of a value, es6 prints a reference to a value.

Commonjs is run time loading, ES6 is compile time output interface;

Require and import performance

Require has slightly lower performance than import.

Since require introduces modules at run time and assigns them to a variable, import only introduces specified modules at compile time based on the interface in import, so performance is slightly higher

conclusion

If this article helped you, please like 👍 and follow ⭐️.

If there are any errors in this article, please correct them in the comments section 🙏🙏.