英文:
Nodejs import trouble
问题
关于大学项目,我需要制作一个带有服务器的网站。目录结构如下:
.
├── HTML/
│ └── ...
├── JS/
│ ├── jsfile.js
│ └── ...
└── Nodejs/
└── nodefile.js
在这个 `jsfile` 中,我们定义了一些类,我们想在 `nodefile` 中使用它们。要如何导入这些类呢?
我们尝试使用 `require`,但然后会出现错误,因为在 `jsfile` 中我们有以下内容:
export {
class1,
class2
}
module.export.Class = class1;
Node 不识别 `export { ... }`,并抛出错误,同时在 Node 中同时使用 `import` 和 `require` 语句也会导致错误。那么,如何在不干扰 JavaScript 文件之间的导入和导出的情况下导入来自 `jsfile` 的类呢?
提前感谢!
英文:
For uni I've got this project where I need to make a website with a server. The fonder looks like this:
.
├── HTML/
│ └── ...
├── JS/
│ ├── jsfile.js
│ └── ...
└── Nodejs/
└── nodefile.js
In this jsfile
we have classes defined which we would like to use in nodefile
> how would we import these classes?
We tried to use require, but then we get errors regarding the fact that we have this in the jsfile:
export {
class1,
class2
}
module.export.Class = class1;
node does not recognise the export { ... }
, and throws an error
and using import
and require
statements simultaneously in node gives errors aswell. So how do we import the classes from the jsfile without interfering with the imports and exports between js files?
Thanks in advance!!
答案1
得分: 0
你应该在package.json中有"type": "module"
时使用import
语法。如果没有,你应该使用require
语法。
通常不建议同时使用require
和import
语句,不是最佳实践,但是有一种方法。
import { createRequire } from "module";
const require = createRequire(import.meta.url);
使用这种方法,你可以像这样使用require
:
const data = require("./data.json");
更多信息可以在这里找到。
再次强调,这不是推荐的做法,建议要么坚持使用require
,要么坚持使用import
。
英文:
You should use import
syntax when you have "type": "module"
in the package.json. If not, you should use the require
syntax
Having both require and import statements are generally not recommended and not best practice but yes there is a way.
import { createRequire } from "module";
const require = createRequire(import.meta.url);
With this you could use require as such:
const data = require("./data.json");
More info of that can be found here
Again, this is not recommended, I suggest that you either stick with require
or stick with import
all the way
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论