繁体   English   中英

将一个js文件包含在另一个文件中的正确方法是什么?

[英]What is the correct way to include one js file in another?

以下 JavaScript 代码有效:

let Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})

和 npx npx jest给我一个绿条。

$ npx jest
 PASS  test/example.spec.js
  ✓ It is not easy being green (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.351 s, estimated 1 s
Ran all test suites.

但是,每当我尝试将 class 与测试分开时,我都会遇到各种错误:

最常见的是不允许在模块外使用 import。

或者该Example不是构造函数。

我想要做的是将所有不是三线测试的东西从我上面发布的 JavaScript 文件中移出

如果这是 Java,我会将这些内容移动到单独的.java文件中,然后在我的测试中import该文件。

如果这是 C 将涉及 linker 和#include

我尝试的是创建一个Example.js文件:

let Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

然后在测试中require它:

let Example = require('Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})

但这让我抱怨Example不是构造函数,我想这是真的。 它是一个 class,它可能具有某种相当惰性的默认构造函数。

我也尝试用import替换require

import('Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
})

但这会引起有关不允许在模块外使用import的投诉。

是否可以将笑话测试与 JavaScript 中正在测试的代码分开?

Javascript 中没有#include - 它使用模块系统代替您export要共享的内容。

最好学习该语言提供的工具,而不是试图强迫它以不同语言的方式做某事。

另外,请注意 nodejs 中有两种类型的模块,使用require()module.exports的 CommonJS 模块和使用importexport的 ESM 模块。 您的项目似乎是为 CommonJS 设置的,因此除非您想将项目配置为 ESM 模块项目,然后使用 ESM 规则进行导入和导出,否则您将使用它。

对于 CommonJS 项目:

const Color = require('color');

class Example {
    its_not_easy_being_green() {
        return Color('green');
    }
}

module.exports.Example = Example;

然后,在您的主文件中:

const { Example } = require('./Example.js')

test('It is not easy being green', () => {
    expect(new Example().its_not_easy_being_green()).toBeDefined();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM