• webpacck打包完react后引入到html文件中报错:Target container is not a DOM element...


    手动写了一个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>

  • 相关阅读:
    环境变量
    多重继承
    参数检查(@property)
    限制属性绑定(__slots__)
    实例属性和类属性
    2017-11-28 中文编程语言之Z语言初尝试: ZLOGO 4
    2017-10-23 在各种编程语言中使用中文命名
    2017-11-27 汉化了十数个编译器的前辈的心得体会
    五行
    阴阳
  • 原文地址:https://www.cnblogs.com/shenwh/p/12105147.html
Copyright © 2020-2023  润新知