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

时间:2017-10-31 20:16:39

标签: 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;

1 个答案:

答案 0 :(得分:0)

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

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