我目前正在通过Go服务器渲染Webpack构建文件(bundle.js)。 如何使构建文件热加载,或者需要执行什么操作才能从Go服务器提供热加载文件?
当我使用'npm run start'脚本时,被告知webpack输出是从 http://localhost:3000/dist/
,项目输出来自 http://localhost:3000
我的目录如下
+ public
- bundle.js
+ src
- App.js
- index.js
- index.html
- package.json
- server.go
- webpack.config.js
// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>React Starter</title>
</head>
<body>
<div id="root"></div>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<script src="/public/bundle.js"></script>
</body>
</html>
// webpack配置
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["@babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
resolve: { extensions: ["*", ".js", ".jsx"] },
output: {
path: path.join(__dirname, "/public"),
publicPath: "/public/",
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname, "/"),
port: 3000,
publicPath: "http://localhost:3000/dist/",
hotOnly: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
// package.json
{
"name": "r-proj",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --mode development",
"build": "webpack --mode development",
"a": "webpack-dev-server --content-base src --hot --inline"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.1.0",
"@babel/core": "^7.1.0",
"@babel/preset-env": "^7.1.0",
"@babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.2",
"css-loader": "^1.0.0",
"style-loader": "^0.23.0",
"webpack": "^4.19.1",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.8"
},
"dependencies": {
"react": "^16.5.2",
"react-dom": "^16.5.2"
}
}
// server.go
func handler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("./index.html")
t.Execute(w, "")
}
func main() {
http.HandleFunc("/", handler)
fs := http.FileServer(http.Dir("./public/"))
http.Handle("/public/", http.StripPrefix("/public", fs))
log.Fatal(http.ListenAndServe(":8080", nil))
}
谢谢。