【发布时间】:2017-02-13 12:13:16
【问题描述】:
您好,这是我正在尝试设置以与 webpack 一起使用的快速服务器。
const Server = require('./server.js')
const path = require('path')
const port = (process.env.PORT || 3001)
const app = Server.app()
if (process.env.NODE_ENV !== 'production') {
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const config = require('./webpack.config.js')
const compiler = webpack(config)
app.use(webpackHotMiddleware(compiler))
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: path.join(__dirname, '/build')
}))
}
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
./app.js
const path = require('path')
const express = require('express')
module.exports = {
app: function () {
const app = express();
const indexPath = path.join(__dirname, '/build/index.html');
const publicPath = express.static(path.join(__dirname, '/build'));
app.use('/build', publicPath);
app.get('/', function (_, res) { res.sendFile(indexPath) });
return app;
}
}
./server.js
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, '/build');
var config = {
entry: path.resolve(__dirname,'app/main.js'),
output: {
path: BUILD_DIR,
filename: 'bundle.js',
publicPath: '/build/'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['es2015', 'react']}},
{ test: /\.sass$/, loaders: ['style', 'css', 'sass'] },
{ test: /\.css$/, loader: "style!css" },
{ test: /\.png$/, loader: "url-loader?prefix=img/&limit=5000" },
{ test: /\.svg$/, loader: 'babel!svg-react' }
]
}
};
module.exports = config;
./webpack.config.js
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
</head>
<body>
<div id="app">
<script type="text/javascript" src="bundle.js"></script>
</div>
</body>
</html>
./build/index.html
当我运行 node app.js 时,它会找到 index.html 页面,但我收到 404 错误“找不到 bundle.js”,我确定某处我指向了错误的目录,但我似乎无法解决!
【问题讨论】:
-
您的
bundle.js保存在哪里?它在你的BUILD_DIR(或)其他地方吗? -
bundle.js 应该由 webpack 输出到 BUILD_DIR (./build)
-
在这种情况下,在您的
var config声明中,您的filename应该更改为filename: './bundle.js',对吧? -
既然我通过了路径应该没问题,但我还是尝试了,但仍然没有
-
好的,最后一个问题,您的
build.html和您的bundle.js文件是否位于同一目录中?
标签: javascript node.js express webpack webpack-dev-server