I recently created my webpack config file:
const path = require("path");
const SRC_DIR = path.join(__dirname, "/client/src");
const DIST_DIR = path.join(__dirname, "/client/dist");
module.exports = { entry: `${SRC_DIR}/index.jsx`, output: { filename: "bundle.js", path: DIST_DIR }, module: { rules: [ { test: /\.jsx?$/, include: SRC_DIR, exclude: /node_modules/, loader: "babel-loader", query: { presets: ["react", "es2015"] } } ] }, mode: "development"
};This one works well and is bundling the jsx file:
import React from "react";
import ReactDOM from "react-dom";
class MainApp extends React.Component { render() { return ( <div className="content"> <h1>Hello World</h1> </div> ); }
}
ReactDOM.render(<MainApp />, document.getElementById("app"));And now inside the html file I included the bundle file with the div id app.
<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>REACT TEST</title> <script src="./bundle.js"></script>
</head>
<body> <div></div>
</body>
</html>When I tried to run this it seems it did not work and I got the error:
Uncaught Error: Target container is not a DOM element. at invariant (invariant.js:42) at legacyRenderSubtreeIntoContainer (react-dom.development.js:17116) at Object.render (react-dom.development.js:17195) at eval (index.jsx:48) at Object../client/src/index.jsx (bundle.js:97) at __webpack_require__ (bundle.js:20) at bundle.js:84 at bundle.js:87
invariant @ invariant.js:42What am I missing here? Why I am getting this error?
42 Answers
The way you have it it runs before you even have DOM.
You should include it in the bottom like so:
<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>REACT TEST</title>
</head>
<body> <div></div> <script src="./bundle.js"></script>
</body>
</html> You are inserting your React script before the initialization of the container. Make it like this:
<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>REACT TEST</title>
</head>
<body> <div></div> <script src="./bundle.js"></script>
</body>
</html>