我正在尝试为我想要构建的网站设置 Webpack 配置。我想将SASS编译为CSS并将其放入dist文件夹中。当我运行
npm run build
时,它工作正常,但是当我运行 npm run watch
来触发 Webpack-dev-server 时,它不会将 index.js 编译为 bundle.js,并且不会出现在 dist 文件夹中。我的 webpack.config.js 有问题吗?
index.html
<html>
<head>
<title>Getting Started</title>
<link rel="stylesheet" href="dist/css/main.min.css">
</head>
<body>
test
<script src="dist/scripts/bundle.js"></script>
</body>
</html>
webpack.config.js
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const extractSass = new ExtractTextPlugin({
filename: "../css/main.min.css",
disable: process.env.NODE_ENV === "development"
});
module.exports = {
entry: './src/scripts/index.js',
output: {
path: path.resolve(__dirname, 'dist/scripts'),
filename: 'bundle.js',
publicPath: 'dist/scripts'
},
module: {
rules: [
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
}
]
},
plugins: [
extractSass
]
};
package.json
{
"name": "project1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --optimize-minimize",
"watch": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^0.28.9",
"extract-text-webpack-plugin": "^3.0.2",
"node-sass": "^4.7.2",
"sass-loader": "^6.0.6",
"style-loader": "^0.20.2",
"webpack": "^3.11.0",
"webpack-dev-server": "^2.11.1"
},
"dependencies": {}
}
开发服务器有选项 写入磁盘
module.exports = { //... devServer: { writeToDisk: true } };
检查一下: https://webpack.js.org/configuration/dev-server/#devserverwritetodisk-
webpack-dev-server
凭记忆服务。如果您想在开发过程中使用 webpack-dev-server
查看磁盘上的文件,则需要同时运行标准 webpack
构建。有关详细信息,请参阅此答案。
您可以在该 URL 中查看 webpack-dev-server 生成的 URL。
http://localhost:8080/webpack-dev-server(根据需要更改主机和端口)
webpack-dev-server 不会将文件写入磁盘,但您可以在那里看到它们。
您已经注意到 dist/scripts 没有更新。
正如其他人所说,webpack-dev-server 仅将其保留在内存中。
但是你可以利用这一点。
将其添加到您的 webpack.config.js 中:
module.exports = {
...
devServer: {
open: true, // Automatically open the browser
hot: true, // Automatically refresh the page whenever bundle.js
publicPath: '/dist/scripts',
},
...
};
publicPath: '/dist/scripts'
这就是神奇的地方。
默认情况下,webpack-dev-server 在 localhost:8080/
上提供配置的
output.filename(例如
localhost:8080/bundle.js
)。localhost:8080/dist/scripts/
上提供内容(例如 localhost:8080/dist/scripts/bundle.js
)。<script src="dist/scripts/bundle.js"></script>
。
注意:您必须通过
localhost:8080
访问您的index.html才能完成这项工作。file://...
或不同的主机/端口访问将不起作用,因为它将在您的系统上查找实际文件(当然不会更新)。
或者,如果您有
output: { filename: '/dist/scripts/bundles.js } }
而不是 output: { filename: 'bundles.js } }
,那么 publicPath 将是不必要的。
要过滤掉 Hot Module Replacement 文件(例如
main.426e51f98113c94f78fa.hot-update.js
)可以使用:
devServer: {
devMiddleware: {
writeToDisk: (pathToFile) => !( /hot-update/.test(pathToFile) ),
}
},