1

首先,我在這裏發現了許多類似的主題,但即使在提及它們之後,我仍然無法完成它的工作。我的webpack-dev-middleware設置無法獲取/錯誤

所以,我的問題只是當我在運行我的快遞服務器(使用npm run serve)後訪問localhost:3000時,我在Chrome中獲得Cannot GET /。這並不是說它無法找到bundle.js文件;它根本找不到index.html。

當我在package.json文件中運行npm run serve腳本時,我在服務器控制檯上看不到任何錯誤。 Webpack構建(從Webpack-dev-middleware調用)日誌也不會顯示錯誤。

如果我直接從終端運行webpack-dev-server並訪問相同的URL,它會正常工作。 (我在webpack.config.js覆蓋了主機和端口,以配合我使用的Express服務器的那些,通過devServer選項。)

我在做什麼錯?

文件夾結構

/client 
    /main.js  
/dist 
    /index.html 
    /assets/ 
/server 
    /server.js 
/webpack.config.js 
/package.json 

webpack.config.js

const path = require('path'); 

module.exports = { 
    entry: './client/main.js', 

    output: { 
    path: path.resolve(__dirname, 'dist/assets'), 
    filename: 'bundle.js', 
    publicPath: '/assets/' 
    }, 

    module: { 
    rules: [ 
     { 
     use: 'babel-loader', 
     test: /\.jsx?$/, 
     exclude: /node_modules/, 
     }, 
     { 
     use: ['style-loader', 'css-loader', 'sass-loader'], 
     test: /\.scss$/ 
     } 
    ] 
    }, 

    devServer: { 
    host: 'localhost', 
    port: 3000, 
    historyApiFallback: true, 
    contentBase: path.resolve(__dirname, 'dist'), 
    } 
}; 

/dist/index.html

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Webpack-Dev-Middleware Test</title> 
    </head> 
    <body> 
    <div id="app-container"> 
    </div> 
    <script src="/assets/bundle.js"></script> 
    </body> 
</html> 

/server/server.js

const express = require('express'); 
const path = require('path'); 
const app = express(); 
const port = process.env.PORT || 3000; 

if (process.env.NODE_ENV !== 'production') { 

    var webpackDevMiddleware = require("webpack-dev-middleware"); 
    var webpack = require("webpack"); 
    var config = require('./../webpack.config'); 
    var compiler = webpack(config); 
    app.use(webpackDevMiddleware(compiler, { 
    publicPath : config.output.publicPath, 
    })); 

} else { 

    app.use(express.static(path.resolve(__dirname + '/../dist/'))); 
    app.get('*', (req, res) => { 
    res.sendFile(path.resolve(__dirname + '/../dist/index.html')); 
    }); 

} 

app.listen(port,() => console.log('Started on port:', port)); 
+0

你的'npm run serve'腳本是什麼? –

+0

@LeeHanKyeol'nodemon server/server.js' –

+0

你說的是'開發'(而不是'生產')環境? –

回答

1

的問題是,你真的不擔任index.html中的WebPack塊的任何地方。您應該使用插件(如html-webpack-loader)在內存上提供它或使用express的靜態函數,我認爲更理想的(更多webpack方式)解決方案是前者。

以下是使用html-webpack-loader的示例。

(as one of the plugins in webpack config.) 

new HtmlWebpackPlugin({ 
    filename: 'index.html', 
    template: './dist/index.html', 
    title: 'Your website' 
}) 
+1

明白了。謝謝! –