我使用webpack和HtmlWebpackPlugin将捆绑的js和css注入到html模板文件中.
new HtmlWebpackPlugin({
template: 'client/index.tpl.html',
inject: 'body',
filename: 'index.html'
}),
Run Code Online (Sandbox Code Playgroud)
它会生成以下html文件.
<!doctype html>
<html lang="en">
<head>
...
<link href="main-295c5189923694ec44ac.min.css" rel="stylesheet">
</head>
<body>
<div id="app"></div>
<script src="main-295c5189923694ec44ac.min.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这在访问应用程序的根目录时工作正常localhost:3000/,但是当我尝试从另一个URL访问应用程序时失败,例如,localhost:3000/items/1因为捆绑的文件没有注入绝对路径.加载html文件时,它将在不存在的/items目录中查找js文件,因为react-router尚未加载.
如何让HtmlWebpackPlugin注入具有绝对路径的文件,所以express将在我的/dist目录的根目录中查找它们而不是在/dist/items/main-...min.js?或者也许我可以更改我的快速服务器来解决这个问题?
app.use(express.static(__dirname + '/../dist'));
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
Run Code Online (Sandbox Code Playgroud)
基本上,我只需要得到这条线:
<script src="main...js"></script>
Run Code Online (Sandbox Code Playgroud)
在源的开头有一个斜杠.
<script src="/main...js></script>
Run Code Online (Sandbox Code Playgroud) 我已经开始研究Node JS了.
所以这是我的文件.
的index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="app">
<h1>Hello<h1>
</div>
<script src='assets/bundle.js'></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
app.js
var http = require("http"),
path = require('path')
fs = require("fs"),
colors = require('colors'),
port = 3000;
var Server = http.createServer(function(request, response) {
var filename = path.join(__dirname, 'index.html');
fs.readFile(filename, function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
response.writeHead(200);
response.write(file);
response.end();
});
});
Server.listen(port, function() {
console.log(('Server is running on http://localhost:'+ port + '...').cyan);
Run Code Online (Sandbox Code Playgroud)
webpack.config.js …