0

My problem is in the title. I wrote a class like so:

export default class Vector3 {
  constructor(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
  }

  // object's functions
  magnitude() {
    return Math.sqrt(this.x ** 2 + this.y ** 2 + this.z ** 2);
  }

Pretty basic, and I would like to use it in another:

import Vector3 from '../radiosity/vector3';

const v1 = new Vector3(1, 2, 3);

QUnit.test('magnitude()', function (assert) {
  const result = v1.magnitude();
  assert.equal(result, Math.sqrt(14), '|(1, 2, 3)| equals sqrt(14)');
});

But when I run my QUnit test, it gives me this:

`SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:892:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
    at Module.load (internal/modules/cjs/loader.js:812:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:849:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at run (/home/thomas/Code/GitKraken/Slow-light-Radiosity/node_modules/qunit/src/cli/run.js:55:4)
    at Object.<anonymous> (/home/thomas/Code/GitKraken/Slow-light-Radiosity/node_modules/qunit/bin/qunit.js:56:2)
    at Module._compile (internal/modules/cjs/loader.js:956:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)

I saw on internet that this error is very popular but I haven't found a solution yet.

So if someone can help me to figure it out.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Eccsx
  • 185
  • 2
  • 13
  • 1
    Is this for node or the web browser? If it is for the web, specify `type="module` in the script. Or change it to `const Vector3 = require('../radiosity/vector3');` – Mr. Polywhirl Apr 07 '20 at 15:51
  • It's for node, I don't run it in a browser. And if I replace the line with the 'require', it gives me **SyntaxError: Unexpected token 'export'** in Vector3 class – Eccsx Apr 07 '20 at 15:52
  • Try adding the option `--experimental-modules` when executing node – Rashomon Apr 07 '20 at 16:03
  • Does this answer your question? [Node.js - SyntaxError: Unexpected token import](https://stackoverflow.com/questions/39436322/node-js-syntaxerror-unexpected-token-import) – Rashomon Apr 07 '20 at 16:04

1 Answers1

0

You are exporting an ES6 module, when Node understands CommonJS.

class Vector3 {
  constructor(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
  }

  magnitude() {
    return Math.sqrt(this.x ** 2 + this.y ** 2 + this.z ** 2);
  }
}

module.exports = Vector3;

Then you can import it via:

const Vector3 = require('../radiosity/vector3')

Additional information

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132