语法错误:无法在模块外部使用 import 语句。真的吗?
与语法错误:无法在模块外部使用 import 语句,但大大简化以专注于问题的一个特定方面。
那么,如果我正在编写基于 Nodejs 的应用程序,我真的不能在那里使用新的 EMS import
语句吗?
这是我的基于 Nodejs 的应用程序 (index.js
) 的极其简化的版本:
import Database from 'better-sqlite3';
const db = new Database('foobar.db', options);
这是我得到的:
(node:1) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/app/index.js:1
import Database from 'better-sqlite3';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1032:15)
at Module._compile (node:internal/modules/cjs/loader:1067:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
我确实想要使用 加载 ES 模块新的 EMS import
语法,但我自己不是在编写模块,而是在编写应用程序。因此,我觉得将 "type": "module"
放入 package.json
或使用 .mjs
扩展名是错误的,这强调了它的ES 模块。
感觉不太对——之前没有人将 Express Web 应用程序称为模块。
Exact same ask as SyntaxError: Cannot use import statement outside a module, but much simplified to focus on one specific aspect of the problem.
So, if I'm writing my nodejs based apps, is it really so that I cannot use the new EMS import
statements there?
Here is the extremely simplified version of my nodejs based app (index.js
):
import Database from 'better-sqlite3';
const db = new Database('foobar.db', options);
Here is what I get:
(node:1) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/app/index.js:1
import Database from 'better-sqlite3';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1032:15)
at Module._compile (node:internal/modules/cjs/loader:1067:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
I do want to load the ES module using the new EMS import
syntax, but I'm not writing a module myself, but an app instead. Thus I feel wrong to put "type": "module"
in the package.json
or use the .mjs
extension, which stresses that its an ES module.
It just doesn't feel right -- nobody has called an express web application a module before.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论