错误:模块解析失败,当我构建我的ReactJS项目时

huangapple go评论70阅读模式
英文:

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(&#39;items-list&#39;));
| root.render(
&gt;  &lt;React.StrictMode&gt;
|     &lt;App /&gt;
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(&#39;items-list&#39;));
| root.render(
&gt;  &lt;React.StrictMode&gt;
|     &lt;App /&gt;
|   &lt;/React.StrictMode&gt;

Here is my packag.json file:

{
    &quot;private&quot;: true,
    &quot;scripts&quot;: {
        &quot;dev&quot;: &quot;npm run development&quot;,
        &quot;development&quot;: &quot;mix&quot;,
        &quot;watch&quot;: &quot;mix watch&quot;,
        &quot;watch-poll&quot;: &quot;mix watch -- --watch-options-poll=1000&quot;,
        &quot;hot&quot;: &quot;mix watch --hot&quot;,
        &quot;prod&quot;: &quot;npm run production&quot;,
        &quot;production&quot;: &quot;mix --production&quot;,
        &quot;build&quot;: &quot;webpack&quot;
    },
    &quot;devDependencies&quot;: {
        &quot;axios&quot;: &quot;^0.21&quot;,
        &quot;laravel-mix&quot;: &quot;^6.0.6&quot;,
        &quot;lodash&quot;: &quot;^4.17.19&quot;,
        &quot;postcss&quot;: &quot;^8.1.14&quot;,
        &quot;webpack&quot;: &quot;^5.75.0&quot;,
        &quot;webpack-cli&quot;: &quot;^5.0.1&quot;
    },
    &quot;dependencies&quot;: {
        &quot;react-bootstrap&quot;: &quot;^2.7.0&quot;
    }
}

Following webpack.config.js located in the root directory:

const path = require(&#39;path&#39;);

module.exports = {
  entry: &#39;./client/src/index.js&#39;,
  output: {
    path: path.resolve(__dirname, &#39;build&#39;),
    filename: &#39;bundle.js&#39;
  }
};

index.js located in client/scr/index.js

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom/client&#39;;
import ListItems from &#39;./components/ListItems&#39;;
import &#39;./index.css&#39;;
import App from &#39;./App&#39;;
import reportWebVitals from &#39;./reportWebVitals&#39;;

const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));
const itemsList = ReactDOM.createRoot(document.getElementById(&#39;items-list&#39;));
root.render(
 &lt;React.StrictMode&gt;
    &lt;App /&gt;
  &lt;/React.StrictMode&gt;
);
itemsList.render(
  &lt;React.StrictMode&gt;
    &lt;ListItems /&gt;
  &lt;/React.StrictMode&gt;
);

// 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 &#39;./logo.svg&#39;;
import &#39;./App.css&#39;;
import { BrowserRouter as Router, Route } from &#39;react-router-dom&#39;;

function App() {  
    return (
      &lt;React.StrictMode&gt;
      &lt;div className=&quot;App&quot;&gt;
        &lt;header className=&quot;App-header&quot;&gt;
          &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;
          &lt;Router&gt;
            &lt;Route exact path=&quot;/&quot; component={ListItems} /&gt;
            &lt;Route path=&quot;/items/new&quot; component={NewItem} /&gt;
            &lt;Route path=&quot;/items/:id&quot; component={ViewItem} /&gt;
            &lt;Route path=&quot;/items/:id/edit&quot; component={EditItem} /&gt;
          &lt;/Router&gt;
          &lt;p&gt;
            Edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.
          &lt;/p&gt;
          npm install --save-dev webpack webpack-cli

        &lt;/header&gt;
      &lt;/div&gt;
    &lt;/React.StrictMode&gt; 
  );   
}

export default App;

ListItem.js external component in a component folder

import React, { useState, useEffect } from &#39;react&#39;;
import axios from &#39;axios&#39;;
import { Table, Button } from &#39;react-bootstrap&#39;;
import ItemModal from &#39;./ItemModal.js&#39;;
import { Link } from &#39;react-router-dom&#39;;

const ListItems = () =&gt; {
  const [items, setItems] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);

  useEffect(() =&gt; {
    const fetchItems = async () =&gt; {
      const result = await axios.get(&#39;/api/items&#39;);
      setItems(result.data);
    };
    fetchItems();
  }, []);

  const handleCreate = () =&gt; {
    setSelectedItem(null);
    setShowModal(true);
  };

  const handleEdit = (item) =&gt; {
    setSelectedItem(item);
    setShowModal(true);
  };
  return (
    &lt;React.StrictMode&gt; 
        &lt;div&gt;
            &lt;Link to=&quot;/items/new&quot;&gt;Create Item&lt;/Link&gt;
            &lt;h1&gt;Items&lt;/h1&gt;
            &lt;Button onClick={handleCreate}&gt;Create&lt;/Button&gt;
            &lt;Table striped bordered hover&gt;
                &lt;thead&gt;
                &lt;tr&gt;
                    &lt;th&gt;ID&lt;/th&gt;
                    &lt;th&gt;Name&lt;/th&gt;
                    &lt;th&gt;Actions&lt;/th&gt;
                &lt;/tr&gt;
                &lt;/thead&gt;
                &lt;tbody&gt;
                {items.map((item) =&gt; (
                    &lt;tr key={item.id}&gt;
                    &lt;td&gt;{item.id}&lt;/td&gt;
                    &lt;td&gt;{item.name}&lt;/td&gt;
                    &lt;td&gt;
                        &lt;Button onClick={() =&gt; handleEdit(item)}&gt;Edit&lt;/Button&gt;
                    &lt;/td&gt;
                    &lt;/tr&gt;
                ))}
                &lt;/tbody&gt;
            &lt;/Table&gt;
            &lt;ItemModal
                show={showModal}
                onHide={() =&gt; setShowModal(false)}
                item={selectedItem}
            /&gt;
        &lt;/div&gt;
    &lt;/React.StrictMode&gt; 
  );
};

export default ListItems;

ItemModal.js external component in a component folder

import React, { useState } from &#39;react&#39;;
import axios from &#39;axios&#39;;
import { Modal, Form, Button } from &#39;react-bootstrap&#39;;

const ItemModal = ({ show, onHide, item }) =&gt; {
  const [name, setName] = useState(item ? item.name : &#39;&#39;);

  const handleSubmit = async (event) =&gt; {
    event.preventDefault();
    if (item) {
      await axios.patch(`/api/items/${item.id}`, { name });
    } else {
      await axios.post(&#39;/api/items&#39;, { name });
    }
    onHide();
  };

  return (
    &lt;Modal show={show} onHide={onHide}&gt;
      &lt;Modal.Header closeButton&gt;
        &lt;Modal.Title&gt;{item ? &#39;Edit Item&#39; : &#39;Create Item&#39;}&lt;/Modal.Title&gt;
      &lt;/Modal.Header&gt;
      &lt;Modal.Body&gt;
        &lt;Form onSubmit={handleSubmit}&gt;
          &lt;Form.Group&gt;
            &lt;Form.Label&gt;Name&lt;/Form.Label&gt;
            &lt;Form.Control
              type=&quot;text&quot;
              value={name}
              onChange={(event) =&gt; setName(event.target.value)}
            /&gt;
          &lt;/Form.Group&gt;
          &lt;Button type=&quot;submit&quot;&gt;Save&lt;/Button&gt;
        &lt;/Form&gt;
      &lt;/Modal.Body&gt;
    &lt;/Modal&gt;
  );
};

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 &lt;name-of-your-app&gt; 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 = {
...&lt;Your stuff&gt;...
module: {
   rules: [
      {
         test:/\.js$/,
         include: path.resolve(__dirname, &#39;src&#39;),
         loader: &#39;babel-loader&#39;,
         options: {
            presets: [&#39;@babel/preset-env&#39;, &#39;@babel/preset-react&#39;]
         }
      }
   ]
}

I believe this will get you started.

huangapple
  • 本文由 发表于 2023年1月9日 01:09:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定