【发布时间】:2018-11-22 19:50:47
【问题描述】:
我最近创建了我的 webpack 配置文件:
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"
};
这个很好用,正在捆绑jsx文件:
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"));
现在我在 html 文件中包含了带有 div id app 的 bundle 文件。
<!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 id="app"></div>
</body>
</html>
当我尝试运行它时,它似乎不起作用并且我得到了错误:
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:42
我在这里缺少什么?为什么我会收到此错误?
【问题讨论】:
-
该链接讨论了该问题,但专门针对 Webpack。问题的答案要简单得多,请查看此重复的答案或下面给出的答案。
-
只是为了后代添加:我遇到了这个问题,因为我的根 div 的 id 值与 react 在
document.getElementById中寻找的值不同
标签: javascript reactjs webpack