英文:
Error: Module parse failed, when I build my ReactJS project
问题
当我运行npm run build
来构建项目时,它失败了。完整的错误如下,因为我是ReactJS的新手,正在尝试在Laravel中实现CRUD功能。
我尝试从现有的问题中找到解决方案,但没有成功。
您可能需要一个适当的加载器来处理这种文件类型,目前没有配置加载器来处理这个文件。
| const itemsList = ReactDOM.createRoot(document.getElementById('items-list'));
| root.render(
> <React.StrictMode>
| <App />
您可能需要一个适当的加载器来处理这种文件类型,目前没有配置加载器来处理这个文件。
| const itemsList = ReactDOM.createRoot(document.getElementById('items-list'));
| root.render(
> <React.StrictMode>
| <App />
| </React.StrictMode>
这是我的 packag.json 文件:
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"prod": "npm run production",
"production": "mix --production",
"build": "webpack"
},
"devDependencies": {
"axios": "^0.21",
"laravel-mix": "^6.0.6",
"lodash": "^4.17.19",
"postcss": "^8.1.14",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
},
"dependencies": {
"react-bootstrap": "^2.7.0"
}
}
以下是位于根目录中的 webpack.config.js:
const path = require('path');
module.exports = {
entry: './client/src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
}
};
index.js 位于 client/src/index.js
:
import React from 'react';
import ReactDOM from 'react-dom/client';
import ListItems from './components/ListItems';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
const itemsList = ReactDOM.createRoot(document.getElementById('items-list'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
itemsList.render(
<React.StrictMode>
<ListItems />
</React.StrictMode>
);
reportWebVitals();
App.js 位于 client/src/app.js
:
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
return (
<React.StrictMode>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<Router>
<Route exact path="/" component={ListItems} />
<Route path="/items/new" component={NewItem} />
<Route path="/items/:id" component={ViewItem} />
<Route path="/items/:id/edit" component={EditItem} />
</Router>
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
npm install --save-dev webpack webpack-cli
</header>
</div>
</React.StrictMode>
);
}
export default App;
ListItem.js 位于一个组件文件夹中的外部组件:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Table, Button } from 'react-bootstrap';
import ItemModal from './ItemModal.js';
import { Link } from 'react-router-dom';
const ListItems = () => {
const [items, setItems] = useState([]);
const [showModal, setShowModal] = useState(false);
const [selectedItem, setSelectedItem] = useState(null);
useEffect(() => {
const fetchItems = async () => {
const result = await axios.get('/api/items');
setItems(result.data);
};
fetchItems();
}, []);
const handleCreate = () => {
setSelectedItem(null);
setShowModal(true);
};
const handleEdit = (item) => {
setSelectedItem(item);
setShowModal(true);
};
return (
<React.StrictMode>
<div>
<Link to="/items/new">Create Item</Link>
<h1>Items</h1>
<Button onClick={handleCreate}>Create</Button>
<Table striped bordered hover>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>
<Button onClick={() => handleEdit(item)}>Edit</Button>
</td>
</tr>
))}
</tbody>
</Table>
<ItemModal
show={showModal}
onHide={() => setShowModal(false)}
item={selectedItem}
/>
</div>
</React.StrictMode>
);
};
export default ListItems;
ItemModal.js 位于一个组件文件夹中的外部组件:
import React, { useState } from 'react';
import axios from 'axios';
import { Modal, Form, Button } from 'react-bootstrap';
const ItemModal = ({ show, onHide, item }) => {
const [name, setName] = useState(item ? item.name : '');
const handleSubmit = async (event) => {
event.preventDefault();
if (item) {
await axios.patch(`/api/items/${item.id}`, { name });
} else {
await axios.post('/api/items', { name });
}
onHide();
};
return (
<Modal show={show} onHide={onHide}>
<Modal.Header closeButton>
<Modal.Title>{item ? 'Edit Item' : 'Create Item'}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</Form.Group>
<Button type="submit">Save</Button>
</Form>
</Modal.Body>
</Modal>
);
};
export default ItemModal;
我只想让这个应用程序运行起来。
谢谢!
英文:
When I run npm run build
to build the project, it fails. The full error is shown below as I am new to ReactJS and trying to achieve CRUD functionality with Laravel.
I have tried to find the solution from exisitg questions, but no success.
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
| const itemsList = ReactDOM.createRoot(document.getElementById('items-list'));
| root.render(
> <React.StrictMode>
| <App />
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
| const itemsList = ReactDOM.createRoot(document.getElementById('items-list'));
| root.render(
> <React.StrictMode>
| <App />
| </React.StrictMode>
Here is my packag.json file:
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"prod": "npm run production",
"production": "mix --production",
"build": "webpack"
},
"devDependencies": {
"axios": "^0.21",
"laravel-mix": "^6.0.6",
"lodash": "^4.17.19",
"postcss": "^8.1.14",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
},
"dependencies": {
"react-bootstrap": "^2.7.0"
}
}
Following webpack.config.js located in the root directory:
const path = require('path');
module.exports = {
entry: './client/src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
}
};
index.js located in client/scr/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import ListItems from './components/ListItems';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
const itemsList = ReactDOM.createRoot(document.getElementById('items-list'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
itemsList.render(
<React.StrictMode>
<ListItems />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.
reportWebVitals();
App.js located in client/scr/app.js
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
return (
<React.StrictMode>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<Router>
<Route exact path="/" component={ListItems} />
<Route path="/items/new" component={NewItem} />
<Route path="/items/:id" component={ViewItem} />
<Route path="/items/:id/edit" component={EditItem} />
</Router>
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
npm install --save-dev webpack webpack-cli
</header>
</div>
</React.StrictMode>
);
}
export default App;
ListItem.js external component in a component folder
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Table, Button } from 'react-bootstrap';
import ItemModal from './ItemModal.js';
import { Link } from 'react-router-dom';
const ListItems = () => {
const [items, setItems] = useState([]);
const [showModal, setShowModal] = useState(false);
const [selectedItem, setSelectedItem] = useState(null);
useEffect(() => {
const fetchItems = async () => {
const result = await axios.get('/api/items');
setItems(result.data);
};
fetchItems();
}, []);
const handleCreate = () => {
setSelectedItem(null);
setShowModal(true);
};
const handleEdit = (item) => {
setSelectedItem(item);
setShowModal(true);
};
return (
<React.StrictMode>
<div>
<Link to="/items/new">Create Item</Link>
<h1>Items</h1>
<Button onClick={handleCreate}>Create</Button>
<Table striped bordered hover>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>
<Button onClick={() => handleEdit(item)}>Edit</Button>
</td>
</tr>
))}
</tbody>
</Table>
<ItemModal
show={showModal}
onHide={() => setShowModal(false)}
item={selectedItem}
/>
</div>
</React.StrictMode>
);
};
export default ListItems;
ItemModal.js external component in a component folder
import React, { useState } from 'react';
import axios from 'axios';
import { Modal, Form, Button } from 'react-bootstrap';
const ItemModal = ({ show, onHide, item }) => {
const [name, setName] = useState(item ? item.name : '');
const handleSubmit = async (event) => {
event.preventDefault();
if (item) {
await axios.patch(`/api/items/${item.id}`, { name });
} else {
await axios.post('/api/items', { name });
}
onHide();
};
return (
<Modal show={show} onHide={onHide}>
<Modal.Header closeButton>
<Modal.Title>{item ? 'Edit Item' : 'Create Item'}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={handleSubmit}>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</Form.Group>
<Button type="submit">Save</Button>
</Form>
</Modal.Body>
</Modal>
);
};
export default ItemModal;
I just want to make it run this app.
Thanks!
答案1
得分: 2
看起来你正在尝试从头开始创建一个完整的React应用程序。通常,人们会使用一些工具来为你生成所有的样板代码。reactjs.org 在他们的教程中通常会使用一个叫做 create-react-app 的常见工具。如果你想使用它,运行 npx create-react-app <你的应用程序名称>
将会为你生成所有的核心依赖项以及webpack和babel的默认配置。不过你可能仍然需要安装 react-router-dom。
如果你希望继续使用你现在的方式,问题在于你正在尝试在js文件中使用JSX,而webpack不知道如何处理它。你将需要一个转译器将JSX转换为原生的js代码。Babel 是最受欢迎的选择。为了使它们能够一起工作,你需要采取以下步骤:
- 运行
npm install -D @babel/core babel-loader @babel/preset-env @babel/preset-react
- 看起来你想要使用React、ReactDOM和React Router,但是根据你的package.json文件,你并没有安装这些东西。你需要运行
npm install --save react react-dom react-router-dom
。 - 现在我们已经安装了所有的东西,我们需要配置webpack。在你的webpack.config.js中,你需要添加以下内容:
module.exports = {
...<你的配置>...
module: {
rules: [
{
test:/\.js$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
]
}
我相信这样可以让你开始了。
英文:
It seems you are trying to create an entire React App from scratch. Usually, people use something that generates all the boilerplate code for you. A common one that reactjs.org uses in their tutorial is create-react-app. If you wish to use it, running npx create-react-app <name-of-your-app>
will generate all the core dependencies and default configs for webpack and babel for you. You will still probably need to install react-router-dom though.
If you wish to continue on your journey with what you have, the problem is that you are trying to use JSX in your js file and webpack doesn't know how to handle it. You will need a transpiler to convert the jsx into native js code. Babel is the most popular. To have it all work together, here are the steps you need to take:
npm install -D @babel/core babel-loader @babel/preset-env @babel/preset-react
- It looks like you are trying to use React, ReactDOM, and React Router, but looking at your package.json you have none of those things installed. You will need to do
npm install --save react react-dom react-router-dom
. - Now that we have installed everything, we need to configure webpack. In your webpack.config.js, you will need to add the following:
module.exports = {
...<Your stuff>...
module: {
rules: [
{
test:/\.js$/,
include: path.resolve(__dirname, 'src'),
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
]
}
I believe this will get you started.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论