0

I cannot import the Observable object from RXJS. I get a syntax error message :

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...

My package.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"
  }
}

I installed rxjs with npm. I do not understand why it does not work. Could you help me please ? Thank you in advance. Regards

Rudy
  • 1
  • 1
  • 1
    Does this answer your question? [Node.js - SyntaxError: Unexpected token import](https://stackoverflow.com/questions/39436322/node-js-syntaxerror-unexpected-token-import) – VLAZ Apr 02 '20 at 06:26

1 Answers1

0

NodeJS does not support EcmaScript modules by default. The feature is experimental at the moment. Try to rename your JavaScript files to .mjs and run

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

This should do the trick. If your package.json file contains the field

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

you should don't need to rename the files. The docs can be really helpful here.

If you are using TypeScript make sure to have the following code in your tsconfig.json file

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

You should be able to vary the EcmaScript version without problems but the module set to commonjs is important.

Felix Lemke
  • 6,189
  • 3
  • 40
  • 67