Home > Blockchain >  Can't run React app using WebPack because it's looking in the public directory
Can't run React app using WebPack because it's looking in the public directory

Time:02-11

I'm a backend developer, trying to pick up and run a simple React app, but having some difficulty. Despite several hours of research and ramping up on React/WebPack/etc, I can't figure the below out:

If I just run npm run build && npm run start I get a 404. I eventually figured out this is because it's looking for index.html in the public subdirectory, whereas it lives in the root folder at present.

I moved it into a public folder, and this time it renders an empty page. I figured out this is because the HTML references ./dist/bundle.js. But of course the dist folder is off the root (where index.html used to be, but it's now in public). I did try ../dist/bundle.js, but unsurprisingly this didn't work.

So, I can either have index.html in the root directory, and find a way to get WebPack to find it there, or put it in public and find a way to reference dist/bundle.js.

As an experiment, I manually copied bundle.js into public and updated the script tag, and it seemed to work fine.

I'm sure this is simple to folk who have lived in this stack for a while. I'm including config files below if it helps.

package.json:

{
  // <Omitted>
  "main": "index.tsx",
  "scripts": {
    "build": "webpack",
    "watch": "webpack --watch",
    "start": "webpack serve --open"
  },
  "dependencies": {
    // <Omitted>
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@types/node": "^17.0.5",
    "@types/react-dom": "^17.0.11",
    "ts-loader": "^9.2.6",
    "typescript": "~4.5.5",
    "webpack": "^5.68.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.7.4"
  }
}

WebPack.config.js:

"use strict";

const path = require("path");

module.exports = {
  entry: "./src/index.tsx",
  devServer: {
    port: 3000
  },
  output: {
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader"
      }
    ]
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"]
  },
  mode: "development",
  devtool: "source-map"
};

CodePudding user response:

I'm not convinced this is the "proper" solution, but I got this working by adding the following to my WebPack.config.js:

  devServer: {
    static: __dirname,
  },
  • Related