繁体   English   中英

如何在节点中导出 JS 模块

[英]how export JS module in node

我正在尝试在测试文件中导入 string.prototype.method。

模块文件:

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

测试文件:

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

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

当我运行 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.

我不明白,也许导出时 string.prototype 方法有问题?

感谢@vitaliykotov,我学到了以前不知道的东西。

一切都很漂亮,但是现在当我尝试使用此文件进行 npm 测试时:

const test = require('ava')

结果是这样的:

> 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

正如错误中所说,您的模块(以及默认情况下 Node 中的所有模块)是 CommonJS 模块。 所以要从中导入一些东西,你应该使用require() function。 可以告诉 Node 将模块视为ECMAScript ,但是所有模块都应该以这种方式定义

暂无
暂无

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

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