我无法正确导入模块

问题描述 投票:0回答:1

我的问题是标题。我写了这样的课:

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);
  }

非常基本,我想在另一个中使用它:

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)');
});

但是当我运行QUnit测试时,它给了我这个:

`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)

我在互联网上看到此错误非常普遍,但尚未找到解决方案。

所以如果有人可以帮助我解决这个问题。

node.js qunit
1个回答
0
投票

当Node理解CommonJS时,您正在导出ES6模块。

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;

签出此:https://www.sitepoint.com/understanding-module-exports-exports-node-js/

© www.soinside.com 2019 - 2024. All rights reserved.