javascript - 将commonjs模块与ES6模块混合以导出两个函数

标签 javascript ecmascript-6 commonjs es6-module-loader

我有这个文件:commonutils.js

import { isBoolean, isNil  } from 'lodash'; // isNil , check undefined or null
import moment from 'moment';

let dateToISO = function (dateString) {
  if (!dateString) {
    return null;
  }
  let p = dateString.split(/\D/g);
  return [p[2], p[1], p[0]].join('-');
}
let ISOtoDate = function (dateString) {
  if ( isNil(dateString) || dateString === '') {
    return  '';
  }
  return moment(dateString).format('DD-MM-YYYY');
}

module.exports.dateToISO = dateToISO;
module.exports.ISOtoDate = ISOtoDate;

当我尝试在 webstorm 上导入时,webstorm 在我键入时完成要导入的名称:

import { dateToISO,  ISOtoDate } from './commonutils';

但是当我执行时,我收到此错误:

./src/utils/validators.js
8:10-19 './commonutils' does not contain an export named 'dateToISO'.

我做错了什么?

更新:

用这个导入:

const { dateToISO,  ISOtoDate } = require('./commonutils');

我明白了:

TypeError: Cannot set property 'dateToISO' of undefined
> module.exports.dateToISO = dateToISO;

最佳答案

您正在使用带有 ES6 导入的 CommonJS 模块导出语法。对于导入,您需要执行以下操作:

const { dateToISO,  ISOtoDate } = require('./commonutils');

关于javascript - 将commonjs模块与ES6模块混合以导出两个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47043858/

相关文章:

javascript - Browserify 外部需要 Grunt-Browserify

javascript - 当我们为元素设置新的 html 时,如何保存事件处理程序?

javascript - jQuery DataTables fnCreatedCell 未被调用

javascript - 使用 jquery 移动 div

javascript - 为什么第二个操作比第一个快?

javascript - 如何在 CommonJS 项目中包含 Epson SDK for JavaScript

javascript - CommonJs模块系统中 "module.exports"和 "exports"之间的区别

javascript - 如何在 JavaScript 中从 EL 获取值

javascript - 使用多个可选参数重构 JS 方法

javascript - javascript const 真的是常量吗?在还原?