首页 > 解决方案 > 获取结果无法从 Webpack 获取 /

问题描述

我正在尝试webpack使用我的 React 项目运行,但是当我使用推荐运行我的项目时,webpack-dev-serve我得到了错误:

Cannot GET /

我尝试查看http://localhost:8080/webpack-dev-serve以检查构建的路由是否不正确,但我没有发现问题。

有人可以帮我解决这个问题吗?我正在四处寻找几个小时

webpack.config.js

const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    entry: './src/index.tsx',
    devtool: 'eval-source-map',
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
    },
    module: {
        rules:[
            {
                test: /\.(ts|js)x?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader:'babel-loader',
                    },
                ],
                include:[path.resolve(__dirname, 'src')],
            },{
                test: /\.css$/,
                use:['style-loader', 'css-loader'],
                include:[path.resolve(__dirname, 'src')],
            },{
                test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
                type:'asset/resource',
                include:[path.resolve(__dirname, 'src')],
            },
        ],
    },
    output: {
        publicPath: '/build/',
        filename: 'bundle.js',
        path: path.resolve(__dirname, '/build/'),
    },
    mode: 'development',
    plugins: [
        new htmlWebpackPlugin({
            template: path.resolve(__dirname, 'build', 'index.html')
        }),
    ],
}

包.json

{
  "name": "react-shopping-bag",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "serve": "webpack-dev-server",
    "build": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.15.8",
    "@babel/plugin-transform-runtime": "^7.15.8",
    "@babel/preset-env": "^7.15.8",
    "@babel/preset-react": "^7.14.5",
    "@babel/preset-typescript": "^7.15.0",
    "@types/react": "^17.0.32",
    "@types/react-dom": "^17.0.10",
    "babel-loader": "^8.2.3",
    "css-loader": "^6.4.0",
    "html-webpack-plugin": "^5.4.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "style-loader": "^3.3.1",
    "typescript": "^4.4.4",
    "webpack": "^5.59.1",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.3.1"
  }
}

http://localhost:8080/webpack-dev-server

http://localhost:8080/build/bundle.js

http://localhost:8080/build/index.html

文件结构

标签: javascriptreactjswebpackwebpack-dev-server

解决方案


推荐阅读