【问题标题】:require working but import not working需要工作但导入不起作用
【发布时间】:2016-11-24 06:09:53
【问题描述】:

我有一个 actions.js 文件,它正在导出这样的操作

export var toggleTodo = (id) => {
  return {
    type: 'TOGGLE_TODO',
    id
  }
}

但是当我使用 es6 import 导入它时出现错误

Uncaught TypeError: Cannot read property 'toggleTodo' of undefined

但是当我需要它时使用普通的 js 要求它工作得很好!有人可以向我解释为什么会发生这种情况,我的意思是我读到这两个是相同的东西......似乎有些不同?

// var actions = require('actions') working 
// dispatch(actions.toggleTodo(id));

import actions from 'actions' //not working
dispatch(actions.toggleTodo(id));

【问题讨论】:

  • 您已使用requirejs 标记此内容。你真的在使用它吗? (RequireJS是一个特定的产品。它不是“require in JavaScript”的通用简写。它不是指Node.js提供的require。)如果不是,请删除那个标签,因为那只是令人困惑。

标签: es6-module-loader es6-class es6-modules


【解决方案1】:

import 有几种不同的形式,每一种做的事情都略有不同。你正在使用的那个

import actions from 'actions' //not working

用于从actions 模块导入default export。你可以看到complete list in MDN javascript reference

它不起作用,因为您的 action.js 模块可能没有默认导出,而 actions 未定义。

大致对应require调用的形式是这个:

import * as actions from 'actions';

它允许您访问所有导出的值作为actions 的属性:

dispatch(actions.toggleTodo(id));

或者您可以像这样使用命名导入:

import {toggleTodo} from 'actions';

那么你可以直接使用toggleTodo

dispatch(toggleTodo(id));

【讨论】:

  • 这对我来说不适用于 Typeorm。从'typeorm'导入*作为typeorm;仍然给出同样的错误。
猜你喜欢
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多