node.jsqunit

I can't import a module without errors


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.


Solution

  • 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