在我的项目中,当我尝试加载模块时,我总是遇到错误。当我尝试从 node_modules 文件夹导入它时,出现错误:
Uncaught Error: Module not found: "./MyLibrary". Parent module folder was: "/"
但是,如果我将
MyLibrary.js
文件复制到同一目录,那么它可以正常导入。
有什么我想念的吗?
代码如下:
不工作:
const MyLibrary = require("MyLibrary");
工作:
const MyLibrary = require("./MyLibrary").MyLibrary;
Package.json:
{
"name": "project",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"MyLibrary": "^1.4.8"
}
}
更新:
如果我写出库的整个路径,它就会开始工作,但随后会在其中一个依赖项上出错。
const Sval = require('/node_modules/MyLibrary/dist/MyLibrary');
错误:
Uncaught Error: Module not found: "MyLibraryDependen". Parent module folder was: "/node_modules/MyLibrary/dist".
更新 2:
看起来我所在的环境不像 nodejs 那样进行模块解析。
...你需要使用像 webpack 这样的东西来 require() 来自 node_modules 的东西。
就我而言,我工作的环境不进行模块解析。
我找到了 webpack,应该可以解决这个问题。
但我所做的是将 library.js 复制到项目目录和所有引用的类(或将它们放在子文件夹中)并更新库路径。