手动写了一个react程序,用webpack打包后生成了一个bundle,js文件,然后引入到index.html文件夹后,在浏览器打开该html文件,报错Target container is not a DOM element,一直找原因发现是引入bundle.js的顺序不对,应该放在div元素的下方,下面具体看代码
react相关js内容
var React = require('react');
var ReactDom = require('react-dom');
const element = <div>Hello, world</div>;
ReactDom.render(
element,
document.getElementById('root')
)
在这里还要全局安装webapck,输入命令npm i webpack -g即可
package.json内容
{
"name": "start",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "set NODE_ENV=dev && webpack-dev-server --progress --colors"
},
"author": "shen",
"license": "ISC",
"dependencies": {
"@babel/core": "^7.7.7",
"@babel/preset-react": "^7.7.4",
"babel-loader": "^8.0.6",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"webpack": "^4.41.4",
"webpack-dev-server": "^3.10.1"
},
"devDependencies": {}
}
webpack.config.js内容
var webpack = require('webpack');
var path = require('path');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname,'main/js/index.js'),
module: {
rules: [{
test: /.js$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader'
}]
}]
},
output: {
filename: 'bundle.js'
}
}
.babelrc文件内容
{
"presets": ["@babel/react"],
"env": {
"dev": {
"plugins": [["react-transform", {
"transforms": [{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}]
}]]
}
}
}
index.html内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="root"></div>
</body>
//这里一般是会放在head里,就回报错Target container is not a DOM element...,放到元素下边就好了
<script src="dist/bundle.js"></script>
</html>