[英]Cannot find module when trying import from JavaScript files
In my code, I have a directory for example named tree
, and inside tree
there are two js files tree.js
and traversal.js
.在我的代码中,我有一个名为
tree
的目录,在tree
里面有两个 js 文件tree.js
和traversal.js
。
The directory structure is like目录结构就像
/tree
traversal.js
tree.js
traversal.js
function inorderRecursive(root) {
if (!root) return null
inorderIterative(root.left)
console.log(`${root.val} `)
inorderRecursive(root.right)
}
function inorderIterative(root) {
let curr = root
let stack = [curr]
while (stack.length || curr) {
// if the current node exists, push it into the stack (defer it)
// and move to its left child. Same as => inorder(curr.left)
if (curr) {
stack.push(curr)
curr = curr.left
} else {
// otherwise, if the current node is null, pop an element from the stack,
// print it, and finally set the current node to its right child. Same as => inorder(curr.right)
curr = stack.pop()
console.log(`${currNode.val} `)
currNode = currNode.right
}
}
}
export {
inorderIterative,
inorderRecursive,
}
tree.js
import {
inorderIterative,
inorderRecursive,
} from "./traversal"
// and use it here
I referred import and export module from this , but when I execute the file, and the logs say我从这里引用了导入和导出模块,但是当我执行文件时,日志说
$ node tree.js
$节点树.js
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module 'C:\Users\PC_1\desktop\algorithm\techie_delight\js-algo\tree.js'
?[90m at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)?[39m
?[90m at Function.Module._load (internal/modules/cjs/loader.js:725:27)?[39m
?[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)?[39m
?[90m at internal/main/run_main_module.js:17:47?[39m {
code: ?[32m'MODULE_NOT_FOUND'?[39m,
requireStack: []
}
You should definitely make a package.json with你绝对应该用
npm init -y
and change the module type to es6 in the package.json file with并将 package.json 文件中的模块类型更改为 es6
'type': 'module'
With this you essentially enable es6 import/export.有了这个,你基本上启用了 es6 导入/导出。 And I would also add the file extension (.js) in the import statement like this
而且我还会像这样在导入语句中添加文件扩展名(.js)
import {
inorderIterative,
inorderRecursive,
} from "./traversal.js"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.