我正在从头开始制作基于MERN(在前端使用React,在后端使用Express)的应用程序。而且我希望webpack每次保存文件时都重新加载页面。但这不起作用。
我的webpack.config.js
const path = require('path');
const entryFile = path.resolve(__dirname, 'src', 'client', 'app.js');
const outputDir = path.resolve(__dirname, 'public');
module.exports = {
entry: ['babel-polyfill', entryFile],
output: {
filename: 'bundle.js',
path: outputDir
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(scss|css)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader'
}
]
}
]
}
};
我的package.json
{
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "babel-node src/server/app.js",
"prestart": "webpack --mode development"
},
"repository": {
"type": "git",
"url": "git+https://github.com/2u4u/share-book.git"
},
...
"dependencies": {
"express": "^4.16.3",
"webpack": "^4.17.1",
"webpack-dev-server": "^3.1.5"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^1.0.0",
"node-sass": "^4.9.3",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"sass-loader": "^7.1.0",
"style-loader": "^0.22.1",
"webpack-cli": "^3.1.0",
"webpack-command": "^0.4.1"
}
}
我试图在Webpack配置的末尾添加watch: true
,但是那时并没有启动服务器。问题出在哪里?
UPD:问题是否出在server / app.js中?
import express from 'express';
import path from 'path';
const app = express();
const publicPath = path.resolve(__dirname, '..', '..', 'public');
app.use(express.static(publicPath));
app.listen(3000, () => {
console.log(`NEW one MERN Boilerplate listening on port 3000 and looking in folder ${publicPath}`);
});
答案 0 :(得分:1)
在开发脚本中添加-- hot
,如果您使用的是webpack v4,它应该可以正常工作。否则,您可以在webpack配置中添加热模块。
以下应该是您的devDependencies
"dependencies": {
"webpack": "^4.17.1",
"webpack-dev-server": "^3.1.5"
},
并在“启动和预启动”脚本中进行更改:
"prestart": webpack-dev-server --mode development --config webpack.config.js --open --hot
"start": "babel-node nodemon src/server/app.js",
答案 1 :(得分:1)
您可以将watch直接添加到package.json中的prestart脚本
“ prestart”:“ webpack --mode development” --watch --hot
OR
在webpack.config.js文件中添加devserver,如下所示:
devServer: {
contentBase: './public',
hot: true,
watch: true
}
答案 2 :(得分:0)
identity
简单容易。必须将其运行到一个终端中,将服务器运行到另一个终端中。