【问题标题】:Cannot GET / with webpack-dev-server无法使用 webpack-dev-server 获取 /
【发布时间】:2017-09-30 08:37:34
【问题描述】:

我的浏览器怎么会出现Cannot GET /?我认为这是因为我的 webpack-dev-server 没有获取捆绑文件的路径。

devServer/server.js

import config from '../../webpack.config';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import open from 'open';

// template! https://github.com/webpack/webpack-dev-server/blob/master/examples/node-api-simple/server.js

const compiler = webpack(config);
const server = new WebpackDevServer(compiler, {
  contentBase: '../dist/',
  stats: {
    colors: true
  }
});

server.listen(3000, '127.0.0.1' ,err => {
  if (err) {
    console.log(err);
  } else {
    console.log('Dev Server listening on port 3000!\n');
    open("http://localhost:3000");
  }
});

webpack.config.js

import webpack from "webpack";

export default {
  entry: [
    "./app/index"
  ],
  devtool: "inline-source-map",
  output: {
    path: __dirname + "/app/dist/", // Note: Physical files are only output by the production build task `npm run build`.
    publicPath: "/",
    filename: "bundle.js"
  },    
  plugins: [    
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
  module: {
    rules: [
      { test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
        loader: 'babel-loader',
        options: {
          presets: ['env', 'react']
        }
      }}
    ]
  }
};

项目结构

【问题讨论】:

    标签: javascript reactjs webpack ecmascript-6


    【解决方案1】:

    成功构建后,dist 将在当前不存在的 app 文件夹中创建。

    创建文件夹后,您可以直接点击文件路径尝试

    http://localhost:3000/app/dist/yourfile
    

    【讨论】:

    • 嗯,我有点困惑。在我的webpack.config.js 中,path 是__dirname + "/app/dist",我的bundle.js 不应该在/boothie/app/dist/ 中吗?我的publicPath: "/" 应该可以通过localhost:3000/ 访问?
    • 使用开发服务器时,不会在磁盘上创建文件。所有文件都是从内存中创建和提供的。所以生成的文件永远不会有 dist 文件夹。
    【解决方案2】:

    您可以通过localhost:3000访问您的页面

    当您访问此路径时,webpack 开发服务器正在搜索要服务的 index.html 文件(与任何其他 Web 服务器一样)。它找不到 index.html 文件,因为您没有 index.html 文件。 index.html 文件来自您通过属性contentBase: '../dist/', 定义的静态目录。 但正如我所见,您没有名为 dist 的目录,并且此目录中没有 index.html。

    您的脚本是从公共路径提供的,即配置中的/,因此您必须在 index.html 中引用它

    解决方案:

    创建目录 dist 并在其中放置一个 index.html 文件,内容如下:

    <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8">
          <title>Document</title>
        </head>
        <body>
          <script src="/bundle.js"></script>
        </body>
      </html>
    

    欲了解更多信息,请阅读此处: https://webpack.github.io/docs/webpack-dev-server.html

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2022-10-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      相关资源
      最近更新 更多