【问题标题】:Attempted import error: 'formatDate' is not exported from 'src/utils'尝试导入错误:“formatDate”未从“src/utils”导出
【发布时间】:2021-07-05 13:42:20
【问题描述】:

我正在尝试在 React 中创建一个使用库的 utils 文件,但导出的函数对其他文件不可见,并出现以下编译错误:

Attempted import error: 'formatDate' is not exported from 'src/utils'.

一旦我删除了库,代码就会编译并运行良好。此外,如果我直接从我的组件中使用库代码,则代码可以编译并运行。

我进行了很多搜索以了解导出正在使用库的函数但没有发现任何相关问题的问题。

import moment from 'moment';

exports.formatDate = (format, date) => {
  return moment(date).format(format);
}

【问题讨论】:

  • 尝试使用 ES6 语法导出它?喜欢export const formatDate...export function formatDate...

标签: javascript reactjs


【解决方案1】:

改变

exports.formatDate = (format, date)

export const formatDate = (format, date) => {

【讨论】:

  • 效果很好,谢谢。 function 然而是必要的 => export const formatDate = function(format, date)
  • Ops 我的错,是的,需要箭头
【解决方案2】:

exports export 之间存在差异。

export 实际上发送了一个对象,我们可以在适当的文件中使用它。

所以如果你这样做export { formatDate };

那么你可以使用import { formatDate } from './utils;

我们不会将模块导出 (exports) 与 import 一起使用,它必须与 require 语法配对,您可以在早期的 es 版本中找到。

考虑到你的文件是 util,

const formatDate = (format, date) => moment(date).format(format);
export {
     formatDate,
     myOtherUtil,
};

你可以遵循这个结构。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2022-01-12
    • 1970-01-01
    • 2021-01-24
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多