Node.js导入问题

huangapple go评论98阅读模式
英文:

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语法。

通常不建议同时使用requireimport语句,不是最佳实践,但是有一种方法。

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

huangapple
  • 本文由 发表于 2023年3月31日 19:40:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定