1

I have a react app and I have generated a bundle.min.js by creating webapack.config.js which looks like the following:

const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const glob = require('glob');

module.exports = {
  entry: {
    "bundle.js": glob.sync("build/static/?(js|css)/main.*.?(js|css)").map(f => path.resolve(__dirname, f)),
  },
  output: {
    filename: "build/static/js/bundle.min.js",
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  plugins: [new UglifyJsPlugin()],
}

I copied the bundle.min.js from the dist\build\static\js folder and included it in the script tag inside my HTML code index.html as shown below:

<html>
  <head></head>
  <body>
    <h1>Bundle Testing</h1>
    <p>
      Here it comes:
    </p>
    <script src="bundle.min.js"/>
  </body>
</html>

But it doesn't show my app. How should I render my app content inside this HTML code? I'm sure I'm missing something.

Tan
  • 1,433
  • 5
  • 27
  • 47
  • What does your react code looks like? Why don't you use a ready solution like `create-react-app` or `vite`? – Konrad Dec 13 '22 at 20:37
  • I don't see a DOM container in your HTML file. You need an HTML element with an ID that your React app attaches to. From the React Docs: Step 1: Add a DOM Container to the HTML https://reactjs.org/docs/add-react-to-a-website.html – Pete Dec 13 '22 at 20:40
  • @Pete Thanks. So after adding an HTML element ID, do I need to do something in my react app just like they are doing in `like_button.js`. How would my react app recognize the div element since I've `bundle.min.js` – Tan Dec 13 '22 at 20:52
  • @Konrad I have generated it in some other way as well. But there are multiple `.js` files here when I ran the `yarn run build` as shown i nthe image below: https://i.stack.imgur.com/JewQf.png Is this a better approach than going with `webpack config.js`? Is this what you were referring to using `create-react-app` ? – Tan Dec 13 '22 at 20:53
  • Yes exactly; you need to tie the two together. So your HTML file has your root div say `
    ` , and your JS creates the react component and attaches to the div: `const domContainer = document.querySelector('#div');`
    – Pete Dec 13 '22 at 21:41
  • @Pete The way you mentioned to tie two together makes sense. However, I'm wondering if my `bundle.min.js` is getting created using the react app, where exactly I can define something like you suggested `const domContainer = document.querySelector('#div');` ? – Tan Jan 10 '23 at 20:25

0 Answers0