簡體   English   中英

無法使用webpack-dev-server進行獲取

[英]Cannot GET / with webpack-dev-server

我怎么會在瀏覽器中出現“ 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']
        }
      }}
    ]
  }
};

項目結構

在此處輸入圖片說明

成功構建后,將在當前不存在的app文件夾內創建一個文件夾dist

創建文件夾后,您可以嘗試直接點擊文件路徑

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

您可以通過localhost:3000訪問頁面

當您訪問此路徑時,webpack開發服務器正在搜索要提供服務的index.html文件(就像其他任何Web服務器一樣)。 它找不到index.html文件,因為您沒有index.html文件。 index.html文件從您通過屬性contentBase: '../dist/',定義的靜態目錄提供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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM