【发布时间】:2017-10-13 15:40:56
【问题描述】:
预期
我应该能够导出我的 App 组件文件并将其导入到我的 index.js 中。
结果
我收到以下错误
React.createElement: type is invalid -- 期望一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:对象
我的 index.js
const React = require('react');
const ReactDOM = require('react-dom');
const App = require('./components/App');
require('./index.css');
ReactDOM.render(
<App />,
document.getElementById('app')
);
然后在我的 components/App.js 中
const React = require('react');
export default class App extends React.Component {
render() {
return (
<div>
Hell World! Wasabi Sauce!
</div>
);
}
}
// module.exports = App;
如果我取消注释 module.exports = App; 它将起作用,但我正在尝试使用导出语法。让我发疯的是在另一个项目中,我在这里做同样的事情,而且工作正常:(
【问题讨论】:
-
请不要将 CommonJS 模块与 ES6 模块混用。
import/export语法是为 ES6 模块保留的。使用 CommonJS 模块时,只需使用module.exports。 -
我不想混合它们,但由于某种原因,React 不喜欢我的 ES6 导出。在这个项目中,我在其他项目中使用它很好。
-
这可能取决于您的转译器/捆绑器处理 ES6 模块的方式。当路径错误时,'React.createElement: type is invalid' 错误很常见。你能不能
console.log(require('./components/App'))看看导出了什么? -
我知道
Object {__esModule: true, default: function}和default.name是App。我的路径是正确的,因为 commonJS 方式 module.exports 有效。 -
那么你应该使用
const App = require('./components/App').default来获取组件(默认导出)。
标签: javascript reactjs ecmascript-6 export commonjs