简体   繁体   English

如何在节点中导出 JS 模块

[英]how export JS module in node

I'm trying to import a string.prototype.method in a test file.我正在尝试在测试文件中导入 string.prototype.method。

MODULE FILE:模块文件:

module.exports = String.prototype.camelCase = function camelCase() {
  let string = "";
  this.split(" ")
    .map((el, i) => {
      i == 0
        ? (string += el.replace(/^\w/, (c) => c.toLowerCase()))
        : (string += el.replace(/\w/, (c) => c.toUpperCase()));
    })
    .join("");
  return string;
};

TEST FILE:测试文件:

const test = require("ava");
import { camelCase } from "./index.js";

test("test", (t) => {
  t.pass("hello world".camelCase(), "HelloWorld");
});

when I trun npm test that's what ava return:当我运行 npm 测试时 ava 返回:

> js-util-library@1.0.0 test
> ava


  ✖ No tests found in test.mjs

  ─

  Uncaught exception in test.mjs

  file:///home/xlrnz/Documenti/dev/js-util-library/test.mjs:2
  import { camelCase } from "./index.js";
           ^^^^^^^^^
  SyntaxError: Named export 'camelCase' not found. The requested module './index.js' is a CommonJS module, which may not support all module.exports as named exports.

I don't understand, maybe some problem with string.prototype methods on export?我不明白,也许导出时 string.prototype 方法有问题?

Thanks to @vitaliykotov I've learned something that previously I don't know.感谢@vitaliykotov,我学到了以前不知道的东西。

Everything beautiful but now when I try npm test with this file:一切都很漂亮,但是现在当我尝试使用此文件进行 npm 测试时:

const test = require('ava')

that's the result:结果是这样的:

> js-util-library@1.0.0 test
> ava test.js


  ✖ No tests found in test.js

  ─

  Uncaught exception in test.js

  ReferenceError: require is not defined

  › file://test.js:1:14

As said in the error your module(and all modules in Node by default) is CommonJS module.正如错误中所说,您的模块(以及默认情况下 Node 中的所有模块)是 CommonJS 模块。 So to import something from it you should use require() function.所以要从中导入一些东西,你应该使用require() function。 Also it's possible to tell Node to treat modules as ECMAScript , but then all modules should be defined this way可以告诉 Node 将模块视为ECMAScript ,但是所有模块都应该以这种方式定义

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

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