我正在尝试使用React应用程序设置Webpack。就我而言,我没有使用create-react-app,因此我尝试自己进行设置。我看到此错误:
Not recognizing member declaration
还有:
This is what I have in package.json:
{
"name": "testapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"webpack": "webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0"
}
}
这是我的webpack.config.js:
module.exports = {
mode: 'development',
context: __dirname,
entry: './index.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['babel-preset-env', 'babel-preset-react']
}
}
}
]
}
}
这是我的组件正在使用的代码:
import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
state = {
posts: []
}
componentDidMount = () => {
const posts = fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => alert(data))
}
render() {
return (
<div>this is home</div>
)
}
}
export default App
我还是Webpack和Loader的新手,因此对您的帮助表示感谢。
答案 0 :(得分:0)
babel等需要在package.json中成为devDependencies。尝试将babel-polyfill添加到您的开发依赖项中。
答案 1 :(得分:0)
将代码更改为
componentDidMount(){
const posts = fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => alert(data))
}
答案 2 :(得分:0)