【问题标题】:mixing commonjs module with ES6 module to export two functions将 commonjs 模块与 ES6 模块混合以导出两个函数
【发布时间】:2018-04-13 02:54:44
【问题描述】:

我有这个文件: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;

【问题讨论】:

  • 好的,dateToISO 定义在哪里?
  • 我已经用完整代码更新了答案

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


【解决方案1】:

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

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

【讨论】:

  • 谢谢,我现在得到 TypeError: Cannot set property 'dateToISO' of undefined
  • 我对你为什么使用 CommonJS 导出感到困惑。为什么不对这两个函数使用 ES6 导出?
  • 因为我直接用 $ node 执行另一个调用那个库的 js 文件,node 不直接支持,你能修改你的答案吗,只需像 require 一样更改导入,因为显然你不能混合导入和commonjs
猜你喜欢
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 2017-07-08
  • 2016-05-13
相关资源
最近更新 更多