与Webpack捆绑时React不工作

时间:2018-04-16 16:51:18

标签: javascript reactjs webpack

我做了最简单的React实现,我遇到了问题。当我捆绑React,然后打开index.html页面时,它是完全空白的。没有控制台错误,或者说我做错了什么。

这是我的webpack.config.js

Backpack

我的基本index.js文件如下所示:

const path = require('path');

module.exports = {
  entry: './src/client/index.js',
  output: {
    path: path.resolve('src/client/public/bundle'),
    filename: 'build.js'
  },
  module: {
    rules: [
        {
            test: /\.css$/,
            use: [
                { loader: 'style-loader' },
                { loader: 'css-loader' }
            ]
        },
        {
            test: /\.jsx?$/,
            exclude: /node_modules/,
               use: "babel-loader"
            }
        ]
    }
};

当捆绑它并包含在import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Hi</h1>, document.getElementById('app'), ); 标记中时,没有任何反应。我认为这是一个反应问题,因为当我从CDN外部添加<script><script>的{​​{1}}标签时,该程序会按预期工作。

我在捆绑反应方面做错了吗?我希望只有一个包含文件(bundle.js)。我怎样才能做到这一点?

修改

按照Tomasz的建议,我安装了HtmlWebpackPlugin。使用它,它突然起作用......我很困惑,因为几乎没有任何改变。在两者中,我使用的是react.js。无论如何,谢谢。

编辑2

我明白了。我这样调用捆绑的脚本: react-dom.js 而不是: <div id="app"></div> 意思是它没有执行。它现在有效!

1 个答案:

答案 0 :(得分:0)

尝试使用html webpack plugin

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src/client/index.js',
  output: {
    path: path.resolve('src/client/public/bundle'),
    filename: 'build.js'
  },
  module: {
    rules: [
        {
            test: /\.css$/,
            use: [
                { loader: 'style-loader' },
                { loader: 'css-loader' }
            ]
        },
        {
            test: /\.jsx?$/,
            exclude: /node_modules/,
               use: "babel-loader"
            }
        ]
    }
    plugins: [
      new HtmlWebpackPlugin()
    ]
};

它会自动为您的包文件生成带有脚本标记的index.html文件。我认为它应该有助于或至少指出错误。