📜  node.js require 和 ES6 导入导出的区别

📅  最后修改于: 2022-05-13 01:56:47.920000             🧑  作者: Mango

node.js require 和 ES6 导入导出的区别

Node.js 遵循 commonJS 模块系统,它需要包含存在于单独文件中的模块,为此它在 node.js 中提供了“require”“ES6 import and export”等方法。

Require:它是内置函数,它是包含存在于单独文件中的模块的最简单方法。 require 的基本功能是它读取一个 JavaScript 文件,执行该文件,然后继续返回导出对象。它不仅允许您添加内置的核心 Node 模块,还允许您在所需程序中添加基于社区的模块(node_modules)和本地模块。节点中有各种内置模块,如HTTP 模块URL 模块查询字符串模块路径模块等等。

句法:

  • 包含内置模块如下:
    const express = require('express');
  • 包括本地模块如下。例如,您需要“abc”模块,而无需指定路径。
    require('abc');

示例: Node 会依次在 module.paths 指定的所有路径中查找abc.js。

  • 输入:
    require('abc');
    
  • 输出:
    • 如果节点找不到它:
      Error: Cannot find module 'abc'
          at Function.Module._resolveFilename (module.js:470:15)
          at Function.Module._load (module.js:418:25)
          at Module.require (module.js:498:17)
          at require (internal/module.js:20:19)
          at repl:1:1
          at ContextifyScript.Script.runInThisContext (vm.js:23:33)
          at REPLServer.defaultEval (repl.js:336:29)
          at bound (domain.js:280:14)
          at REPLServer.runBound [as eval] (domain.js:293:12)
          at REPLServer.onLine (repl.js:533:10)
      
    • 如果节点找到它:
      // It is the content of the file
      Geeksforgeeks example for require
      

ES6 Import & Export:这些语句用于引用 ES 模块。无法使用这些语句导入其他文件类型。它们仅在 ES 模块中被允许,并且该语句的说明符可以是 URL 样式的相对路径或包名称。

Export语句允许用户将他创建的对象和方法导出到其他程序。例如,如果您分配一个字符串字面量,那么它将将该字符串字面量公开为一个模块。

句法:

  • 用于导入文件。
    // Importing submodule from 
    // 'es-module-package/private-module.js';
    import './private-module.js';
  • 用于导出文件。
    module.exports = 'A Computer Science Portal';

示例:创建两个JS文件,一个用于导入,另一个用于导出,或者您可以使用任何模块导入,因此不需要导出一个。

  • 导出文件名Message.js
    // Exporting module
    module.exports = 'Hello Geek';
    

    导入文件名Display.js

    // Importing module
    var msg = import('./Message.js');
    console.log(msg);
  •        
  • Output:
    Hello Geek

node.js require 和 ES6 导入导出的区别:虽然 require函数和 ES6 导入导出有很多共同点,在代码中看起来执行相同的函数,但它们在很多方面都不同。

REQUIREES6 IMPORT AND EXPORT
Require is Non-lexical, it stays where they have put the file.Import is lexical, it gets sorted to the top of the file.
It can be called at any time and place in the program.It can’t be called conditionally, it always run in the beginning of the file.
You can directly run the code with require statement.To run a program containing import statement you have to use experimental module feature flag.
If you want to use require module then you have to save file with ‘.js’ extension.If you want to use import module then you have to save file with ‘.mjs’ extension.

注意:您必须注意,您不能在您的节点程序中同时使用 require 和 import 并且最好使用 require 而不是 import,因为您需要使用实验模块标志功能来运行导入程序。