[英]React not working when bundled with Webpack
I did the most bare-bones React implementation possible, and I'm running into problems. 我做了尽可能简单的React实现,但遇到了问题。 When I bundle React, then open up the index.html page, it is completely blank.
当我捆绑React时,然后打开index.html页面,它完全空白。 No console errors, or anything to say I did something wrong.
没有控制台错误,也没什么可以说我做错了。
Here is my webpack.config.js 这是我的webpack.config.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"
}
]
}
};
And my very basic index.js file looks like this: 我最基本的index.js文件如下所示:
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hi</h1>,
document.getElementById('app'),
);
When this is bundled, and included in a <script>
tag, nothing happens. 将其打包并包含在
<script>
标记中后,什么也不会发生。 I think this is a react issue because when I externally add <script>
tags for react.js
and react-dom.js
from CDN, the program works as expected. 我认为这是一个反应问题,因为当我从CDN外部为
react.js
和react-dom.js
添加<script>
标记时,该程序将按预期工作。
Am I doing something wrong in terms of bundling react? 我在捆绑方面做错了什么吗? I would like there to only be one included file (bundle.js).
我希望只有一个包含的文件(bundle.js)。 How can I achieve this?
我该如何实现?
Edit 编辑
Following Tomasz' suggestion, I installed HtmlWebpackPlugin. 按照Tomasz的建议,我安装了HtmlWebpackPlugin。 Using that, it suddenly works... I'm very confused, as almost nothing has changed.
使用它,它突然起作用了...我很困惑,因为几乎没有任何变化。 In both, I'm using a
<div id="app"></div>
. 在这两种方法中,我都使用了
<div id="app"></div>
。 Anyway, thanks. 还是谢谢你。
Edit 2 编辑2
I figured it out. 我想到了。 I was calling the bundled script like this:
<script src="bundle.js" />
rather than: <script src="bundle.js"></script>
meaning it did not execute. 我这样称呼捆绑脚本:
<script src="bundle.js" />
而不是: <script src="bundle.js"></script>
意味着它没有执行。 It works now! 现在可以使用!
Try to use html webpack plugin : 尝试使用html webpack插件 :
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()
]
};
It will automatically generate index.html
file with script tag to your bundle file. 它将自动生成带有脚本标签的
index.html
文件到您的捆绑文件中。 I think it should help or at least point to the error. 我认为它应该帮助或至少指出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.