簡體   English   中英

當 react 應用程序未在 localhost:3000 上加載時,如何設置 webpack 和 babel

[英]How do I set up webpack and babel when react app is not loading on localhost:3000

我已經遵循了幾個教程,但似乎都沒有用。 我可以配置 webpack、babel 和一些簡單的 React 組件,但它們不會在我的 localhost:3000 上呈現。 關於我做錯了什么的任何建議,因為終端中沒有控制台日志或錯誤。

package.json

{
  "name": "frontend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {},
  "devDependencies": {
    "@babel/core": "^7.11.0",
    "@babel/preset-env": "^7.11.0",
    "@babel/preset-react": "^7.10.4",
    "babel-loader": "^8.1.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-hot-loader": "^4.12.21",
    "webpack": "^4.44.1",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

.babelrc

{
  "presets":
  [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

webpack.config.js

const webpack = require('webpack');
const path = require('path');


module.exports = {
  devtool: 'inline-source-map',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist',),
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    port: 3000,
    contentBase: './dist',
    hot: true
  },
  module: {
    rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: ['babel-loader']
    }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
};

index.html

<!DOCTYPE html>
<html>
 <head>
 <title>My React Configuration Setup</title>
 </head>
 <body>
 <div id="root"></div>
 <!-- <script src="./dist/bundle.js"></script> -->
 </body>
</html>

索引.js

import React from "react";
import ReactDOM from "react-dom";
import Welcome from './App'

ReactDOM.render(<Welcome />, document.getElementById("root"));

module.hot.accept();

應用程序.js

import React from 'react';

class Welcome extends React.Component {
  render() {
    return <h1>Hello World from React boilerplate</h1>;
  }
}

export default Welcome

你快到了。

  1. 使用來自package.jsonwebpack命令構建bundle.js ,如下所示
  "scripts": {
    "start": "webpack && webpack-dev-server --mode development",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

要么

  "scripts": {
    "build": "webpack",
    "start": "webpack-dev-server --mode development",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  1. 修改webpack.config.js contentBase屬性,因為您的index.html位於根目錄(您可以將其移動到dist
  devServer: {
    port: 3000,
    contentBase: './',
    hot: true
  },
  1. 取消注釋bundle.jsindex.html導入:
 <div id="root"></div>
    <script src="./dist/bundle.js"></script>
 </body>

你可以使用create-react-app來非常快速地初始化一個空的 React 項目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM