为什么使用 Webpack-dev-server 启动 React App 会返回我的目录结构

Why using Webpack-dev-server to start a React App returned my directory structure

我是 webpack-dev-server 的新手,有这个问题。你能解释一下并帮助我修复它吗?

首先,我确定我的应用程序 运行 在没有 webpack-dev-server 的情况下是正确的。但是,使用 Webpack-dev-server 启动 React App 并没有 return 我的 hello world 页面,而是 return 编辑了我的目录结构...我相信我可能会在这里遗漏一些东西。

没有 React,我可以先 运行 webpack --config webpack.config.js 创建我的 bundle.js。然后,执行webpack-dev-server --open打开我的主页。

现在,当我尝试启动 React 应用程序时,此过程对我不起作用。 它将我的开发目录改为如下截图:

我的 hello world 应用是:

Hello.js:

var React = require("react");
var ReactDOM = require("react-dom");

var Hello = React.createClass({
    render: function(){
        var message = "Hello, world!!!!!";
        return (
            <div>
                {message}
            </div>
            );
    }
});


ReactDOM.render(
    <Hello />,
    document.getElementById("root")
);

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>

  </head>
  <body>
    <div id="root"></div>
    <script src= "bundle.js"></script>
    <h2>HEY!</h2>
  </body>
</html>

webpack.config.js:

module.exports = {
    entry: "./app/components/Hello.js",
    output: {
        filename: "public/bundle.js"
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: "babel-loader",
                query: {
                    presets: ["es2015", "react"]
                }
        }]
    }

};

这是因为您的 index.html 在 /public 中,而不是在网站的根目录中。 如果您浏览到 http://localhost:8080/public,您 应该 发现它有效

因为你没有正确设置 webpack 开发服务器。 添加

devServer: {
    contentBase: "./public"
},

查看 webpack-dev-server 配置列表 https://webpack.github.io/docs/webpack-dev-server.html#api

此外,您还必须在 webpack 配置中将 publicPath 设置为 output。因为你在 index.html 中这样调用 bundle.js <script src= "bundle.js"></script>(没有 /public 文件夹)

output: {
    publicPath: '/',
    filename: 'bundle.js'
},

希望对您有所帮助