javascript - Webpack 没有构建最新的更改
问题描述
由于本教程不关注前端部分(webpack 和 babel 等),我从不同的地方挑选了这些步骤。
现在我尝试使用 webpack 和 http-server 构建前端,但我意识到它并没有随着我对文件所做的更改而更新。
webpack.config.js
const path = require('path')
module.exports = {
entry: path.join(__dirname, 'src/js', 'index.js'), // Our frontend will be inside the src folder
output: {
path: path.join(__dirname, 'dist'),
filename: 'build.js' // The final file will be created in dist/build.js
},
module: {
rules: [{
test: /\.css$/, // To load the css in react
use: ['style-loader', 'css-loader'],
include: /src/
}, {
test: /\.jsx?$/, // To load the js and jsx files
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}]
}
}
包.json
{
"name": "test-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.10.2",
"@babel/preset-env": "^7.10.2",
"@babel/preset-react": "^7.10.1",
"babel-loader": "^8.1.0",
"css-loader": "^3.5.3",
"json-loader": "^0.5.7",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"style-loader": "^1.2.1",
"web3": "^0.20.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
},
"directories": {
"test": "test"
},
"dependencies": {},
"description": ""
}
我使用它构建它
npx webpack --config webpack.config.js
然后上桌
http-server dist/
我该如何解决?这甚至是正确的方法吗?谢谢。
解决方案
你已经在你的依赖项中安装了 webpack-cli,所以你不必在命令中添加配置:
首先在你的 Package.json 中添加 Webpack 脚本:
"scripts": {
"watch": "webpack --watch",
},
当你运行npm run watch
--watch webpack 将继续观察任何已解析文件的变化。
对于服务器,我推荐你webpack-dev-server
npm i webpack-dev-server
可用于快速开发应用程序
module.exports = {
//...
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
}
};
并将其添加到您的 npm 脚本中
"scripts": {
"watch": "webpack --watch",
"start": "webpack-dev-server --hot --open",
}
现在我们可以run npm start
从命令行看到我们的浏览器自动加载我们的页面。如果您现在更改任何源文件并保存它们,Web 服务器将在代码编译后自动重新加载。
建议:您必须在 dist 或插件中添加 html 文件以用于 webpack HtmlWebpackPlugin