这是我项目的结构:
hello-world
-- app
-- components
-- main.jsx
-- node_modules
-- public
-- build.js
-- index.html
-- package.json
这是我使用npm安装的:
npm install react react-dom babel-core babel-loader babel-preset-es2015 babel-preset-react webpack --save-dev
npm install --save isomorphic-fetch es6-promise
我使用webpack webpack.config
module.exports = {
entry: './app/components/main.jsx',
output: {
path: './public/',
filename: "build.js",
},
module: {
loaders: [
{
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
的package.json
{
"name": "hello-world",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"build": "webpack -w"
},
"author": "mannuk",
"license": "MIT",
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"react": "^0.14.8",
"react-dom": "^0.14.8",
"webpack": "^1.13.2"
},
"dependencies": {
"es6-promise": "^3.3.1",
"isomorphic-fetch": "^2.2.1"
}
}
这是我构建UI的文件:
main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import 'isomorphic-fetch';
import 'es6-promise';
class Person extends React.Component {
constructor(props){
super(props);
this.state = {people : []};
}
componentWillMount(){
fetch('xxx/people',
method: 'get',
headers: {'token' : 'xxx'}
)
.then((response) => {
return response.json()
})
.then((people) => {
this.setState({ people: people })
})
}
render(){
return <div>
<input type="text" value={this.state.people[0].name}></input>
</div>
}
}
ReactDOM.render(
<Person/>,
document.getElementById('container')
);
如果我尝试通过浏览器运行它失败(未定义提取方法)我还检查了这个相关的帖子ES6 `fetch is undefined`并且我已经包含导入但没有成功。我还包括了es6-promise导入,但它也失败了。
我做错了什么?是配置问题还是什么?当我运行'npm run build'时没有错误,build.js似乎没问题。
答案 0 :(得分:23)
它是导出的默认值,所以......
import fetch from 'isomorphic-fetch'
答案 1 :(得分:3)
为此添加polyfill是正确的方法。看看我最近的一个项目,您只需要进行以下导入;
import promise from 'es6-promise';
import 'isomorphic-fetch';
promise.polyfill();
看起来你的es6-promise导入不正确,需要调用.polyfill()方法。我建议将它们放在应用程序的入口点,因为您只需要导入一次。
我还建议你加入babel polyfill;
import 'babel-polyfill';