【问题标题】:Webpack-dev-server injects bundle in HTML page, but nothing is renderedWebpack-dev-server 在 HTML 页面中注入 bundle,但没有渲染
【发布时间】:2019-01-17 12:25:29
【问题描述】:

当我运行 webpack-dev-server(命令:“webpack-dev-server --mode development --open --progress --hot”)时,我的包被注入到 html 页面中,但没有呈现任何内容。

Webpack.config.js 文件:

var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    devtool: "cheap-eval-source-map",
    entry: path.join(__dirname, 'src', 'App.js'),
    output: {
        path: path.join(__dirname, 'dist'),
        filename: "bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                include: path.join(__dirname, 'src')
            }
        ]
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        inline: true
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, 'src', 'index.html'),
            hash: true,
        })
    ]
}

Index.js 文件:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('app'));

App.js 文件:

从“反应”导入反应;

export default class App extends React.Component {
    render() {
        return (
            <div className="container">
                <h1>React Starter App</h1>
            </div>
        );
    }
}

问题是如果我将 App.js 更改为:

alert("test");

它将在页面上显示警报。

【问题讨论】:

  • 您的index.html 文件是什么样的?你有一个id为app的元素吗?

标签: javascript reactjs webpack webpack-dev-server


【解决方案1】:

在您的webpack.config.js 中,将您的入口点更改为index.js 而不是App.js,因为index.js 处理您的初始渲染:

// webpack.config.js      
entry: path.join(__dirname, 'src', 'index.js');

App.js 中的警报正在显示,因为 App.js 仍在捆绑中。但是,它没有被渲染,因为index.js 中的渲染逻辑没有被 webpack 捆绑和执行。

【讨论】:

  • 这与添加
    到我的 index.html 解决了我的问题。非常感谢!
猜你喜欢
  • 2019-11-22
  • 2017-10-30
  • 2016-09-16
  • 2021-05-16
  • 2018-08-02
  • 2021-11-14
  • 2021-08-10
  • 2016-07-01
  • 1970-01-01
相关资源
最近更新 更多