es6 import from xx✀是怎么实现找到 node

2025-04-13 20:34:23
推荐回答(2个)
回答1:

这个和 ES6 没有关系,是模块系统的约定以及实现。在 node 文档里面详细描述了处理过程。
在 Node.js 模块系统中,如果 require 的模块不是核心模块,而且没有 './' 之类的开头,那就需要从当前 package 的 node_modules 里面找,找不到就到当前 package 目录上层 node_modules 里面取... 一直找到全局 node_modules 目录。

回答2:

util_for_node.js

function log(o) {
console.log(o);
}

module.exports = log;
es6_const_let_node_demo.js

// 在 Node 中使用模块的正确姿势:
const log = require("./lib/util_for_node");
// ES5
var a = 1;
a = a + 1;
log(a); // 2

// ES6
const b = 1;
// b = b + 1; // error : TypeError: Assignment to constant variable.
log(b);

// ES6
let c = 1;
c = c + 1;
log(c);