我在响应和webpack4方面是一个新手,对Javascript也没有太多经验。
运行npm run dev
时出现以下错误(请参阅package.json进一步了解):
ERROR in ./project/frontend/src/components/App.js 6:2
Module parse failed: Unexpected token (6:2)
You may need an appropriate loader to handle this file type.
| import Table from "./Table";
| const App = () => (
> <DataProvider endpoint="api/lead/" render={data => <Table data={data} />} />
| );
| const wrapper = document.getElementById("app");
@ ./project/frontend/src/index.js 1:0-35
Package.json看起来像这样:
{
"name": "django-drf-react-quickstart",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development ./project/frontend/src/index.js --output ./project/frontend/static/frontend/main.js",
"build": "webpack --mode production ./project/frontend/src/index.js --output ./project/frontend/static/frontend/main.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.3.3",
"@babel/preset-env": "^7.3.1",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"babel-plugin-transform-class-properties": "^6.24.1",
"prop-types": "^15.7.2",
"react": "^16.8.2",
"react-dom": "^16.8.2",
"weak-key": "^1.0.1",
"webpack": "^4.29.4",
"webpack-cli": "^3.2.3"
}
}
.babelrc:
{
"presets": [
"@babel/preset-env", "@babel/preset-react"
],
"plugins": [
"transform-class-properties"
]
}
我正在关注本教程: https://www.valentinog.com/blog/tutorial-api-django-rest-react/#Django_REST_with_React_requirements。
编辑: 我的webpack.config.js:
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
};
App.js:
import React from "react";
import ReactDOM from "react-dom";
import DataProvider from "./DataProvider";
import Table from "./Table";
const App = () => (
<DataProvider endpoint="api/lead/" render={data => <Table data={data} />} />
);
const wrapper = document.getElementById("app");
wrapper ? ReactDOM.render(<App />, wrapper) : null;
解决方案: 现在可以了。我在评论中使用了@Reema Parakh的建议,但遇到了新的错误,因此按CRTL-Z直到一切恢复正常,现在可以使用了。我现在不为什么。
答案 0 :(得分:1)
基本上,与适当的加载器一起,您需要将React导入到该文件
import React from 'react'
这样,可以在此文件中使用jsx格式 另外,您的代码段中不包含导入的DataProvider,因此我认为也有必要将其导入到该文件中
答案 1 :(得分:0)
我遇到此错误,对我来说解决的是将.babelrc
和webpack.config.js
与package.json
放在同一文件夹中。我正在学习本教程,它说将它们放在“项目文件夹”中-在本例中是顶级文件夹,而不是名为project
的文件夹!
答案 2 :(得分:0)
将webpack.config.js
与package.json
放在同一文件夹中,如果不能解决问题,请继续删除node_modules
并运行命令npm install
,它将重新安装node_modules
,希望它能解决您的问题。