【发布时间】:2016-02-28 02:56:55
【问题描述】:
我真的很难在 Express + Webpack 中提供静态文件。 该文件是一个普通的 css 样式表,但我无法让 html 页面加载它。
这是我当前的配置:
server.js
var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.config')
var express = require('express')
var app = new express()
var port = 3005
var compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
app.use(webpackHotMiddleware(compiler))
// this should tell express that files located under the /public/ folder are static
app.use(express.static(__dirname + '/public'));
app.use(function(req, res) {
res.sendFile(__dirname + '/index.html')
})
app.listen(port, function(error) {
if (error) {
console.error(error)
} else {
console.info("==> ???? Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
}
})
一个相当标准的webpack.config.js:
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: [ 'babel' ],
exclude: /node_modules/,
include: __dirname
}]
}
}
这是 index.html 文件中包含的 css:
<link ref="stylesheet" type="text/css" href="/styles/style.css">
我有位于public/styles/style.css 的style.css 文件,所以我应该看到它,对吧?
事实上,如果我转到http://localhost:3005/styles/style.css,该文件是可用的并且可以正确提供,但是尝试通过index.html 加载它是行不通的。似乎从未发送过网络请求。
关于如何解决这个问题的任何想法?我是否错过了有关 express/webpack 的一些基本信息?
如果这可能与问题相关,我也在使用 react-router。
【问题讨论】:
标签: css node.js express webserver webpack