Darth Plagueris
Darth Plagueris

Reputation: 339

Webpack Not Serving React Component

I have created my webpack config file below:

const HtmlWebPackPlugin = require('html-webpack-plugin');

module.exports = {
entry: './src/main.js',
output: {
    filename: 'bundle.js'
},
module: {
    rules: [
        {
            test: /\.js$/,
            exclude: '/node_modules/',
            use: [
                {
                    loader: 'babel-loader'
                }
            ]
        },
        {
            test: /\.html$/,
            use: [
                {
                    loader: 'html-loader',
                    options: {minimize: true}
                }
            ]
        }
    ]
},
plugins: [
    new HtmlWebPackPlugin({
        template: './src/index.html',
        filename: './index.html'
    })
]
};

and added all the necessary packages babel with env and react presets. I have my index.html file and TestComponent like below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React 16 Webpack Setup</title>
</head>
<body>
    <script src="bundle.js" type="text/javascript"></script>

    <div id="test">

    </div>
 </body>
</html>

and component code:

import React, { Component } from 'react';

export default class TestComponent extends Component {
render(){
    return (
        <div>
            <h2>React Setup</h2>
        </div>
    )
  }
}

Here's my main.js file where I'm hosting the component:

import React from "react";
import ReactDOM from "react-dom";
import Test from './TestComponent';

ReactDOM.render(<Test/>, document.getElementById("test"));

The problem is that when I run this script from package.json, I don't get any output/dist folder and also the component doesn't render in the browser. On which url do I have to visit to see the output just like with create-react-app?

Upvotes: 0

Views: 612

Answers (1)

Michael Abeln
Michael Abeln

Reputation: 2587

Import your <script> at the bottom of the <body> tag in the HTML.

In your case, the browser is reading through the DOM and finding the <script> tag before it is finding the <div id="text"> node. What this means is that the browser will read through your script, and then try and render your <Test/> component into an HTML node with the id="test". The browser can't find the HTML node with the id="test" though because it hasn't read it yet, so it fails.

Make sense? See below...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React 16 Webpack Setup</title>
</head>
<body>

    <div id="test"></div>

    {* import scripts at the bottom of the body *}
    <script src="bundle.js" type="text/javascript"></script>

 </body>
</html>

Hope this helps, let me know if you're still running into issues.

Upvotes: 1

Related Questions