我在尊重文档的情况下导入Observable时出现语法错误



我无法从RXJS导入Observable对象。我收到一条语法错误消息:

import { Observable } from 'rxjs';
^
SyntaxError: Unexpected token {
at new Script (vm.js:83:7)
at createScript (vm.js:267:10)
at Object.runInThisContext (vm.js:319:10)
at Module._compile (internal/modules/cjs/loader.js:685:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:775:12)
at startup (internal/bootstrap/node.js:300:19)
[nodemon] app crashed - waiting for file changes before starting...

我的包.json:

{
"name": "testrxjs",
"version": "1.0.0",
"description": "",
"main": "myrxjs.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"dependencies": {
"jquery": "^3.4.1",
"nodemon": "^2.0.2",
"rxjs": "^6.5.4",
},
"devDependencies": {
"@babel/preset-react": "^7.9.4"
}
}

我用npm安装了rxjs。我不明白为什么它不起作用。你能帮我吗?提前谢谢。问候

NodeJS默认不支持EcmaScript模块。该功能目前处于试验阶段。尝试将您的JavaScript文件重命名为.mjs并运行

node --experimental-modules ./pathto/script.mjs

这应该奏效。如果您的package.json文件包含字段

{
...
"type": "module"
}

您不需要重命名这些文件。这里的文档非常有用。

如果您正在使用TypeScript,请确保tsconfig.json文件中有以下代码

{
"compilerOptions": {
...
"lib": ["es2017"],
"module": "commonjs",
"target": "es2017"
}
}

您应该能够毫无问题地更改EcmaScript版本,但设置为commonjs的模块很重要。

相关内容

最新更新