【发布时间】:2018-02-13 11:13:39
【问题描述】:
我刚刚使用create-react-app 创建了一个新应用程序。
我创建了一个带有组件的新项目,并使用webpack 将带有babel 的JSX 转换为/dist/bundle.js。
我与npm link 链接了我在新项目中创建的应用程序和组件。
在应用程序中我导入了组件,但我总是收到错误
元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。
打印应用中的组件都是undefined。
这是组件:
index.js
import Root from './Root';
export { Root };
Root.js
import React, { Component } from 'react';
class Root extends Component {
render() {
return (<div>{this.props.children}</div>);
}
}
export default Root;
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
query: {
presets:['react']
}
}
}
]
}
};
package.json
{
"name": "my-comp",
"version": "0.0.1",
"description": "",
"main": "dist/bundle.js",
"dependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"react": "^16.2.0"
},
"devDependencies": {
"webpack": "^3.11.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC"
}
在应用程序中
App.js
import { Root } from 'my-comp';
render() {
return (
<Root>
<span>Hello World</span>
</Root>
);
}
有人知道发生了什么吗?我不能从bundle.js 导入吗?
【问题讨论】:
标签: reactjs npm webpack babeljs react-component