javascript - 如何在没有再次运行命令的情况下使用 webpack-dev-server 自动重建包?
问题描述
我是 webpack 的新手,我正在为我的项目使用 webpack 4。但我有一个问题,我有一些文件脚本。第一次用 webpack 开发服务器构建,运行正常。但是当服务器运行时,我继续创建一个新的文件脚本(例如:c.js),重命名或删除现有文件,服务器不会自动将此脚本构建为 main.js。如何自动 webpack 将我的新文件(c.js)重建为 main.js 而无需再次运行命令?
这是我在 github 上的仓库: https ://github.com/aiduc93/webpack4-scss-pug-es6
您可以按照此步骤重现我的问题:
第 1 步:使用“npm run dev”启动服务器并在浏览器中运行 localhost:3000。
第2步:当服务器运行时,我们创建新文件(c.js),你可以复制我在hide.js或show.js中的代码并将pluginName更改为'anything'(即:pluginName='clickable')
步骤 3:进入 index.pug,创建新的带有数据可点击的 p 标签(即:p(data-clickable) 可点击)
第四步:在浏览器中刷新页面,点击可点击的文字。Js 不会运行,因为它没有重新编译。
这是我的结构
//folder javascript in project
javascript
| hide.js
| show.js
| server.js
//folder dist after build
dist
| main.js
这是 package.json 中的脚本
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --inline --hot",
"build": "webpack --mode production"},
这是 webpack.config.js
const path = require('path');
const glob = require('glob');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
module.exports = {
entry: { main: glob.sync('./src/**/*.js*')} ,
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'main.js',
},
devtool: 'inline-source-map',
watch: true,
module: {
rules: [
{
test: /\.pug$/,
use: ["html-loader", "pug-html-loader"]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract(
{
fallback: 'style-loader',
use: [ 'css-loader', 'sass-loader']
})
},
{
type: 'javascript/auto',
test: /\.json$/,
use: [
{
loader: 'file-loader',
options: {
name: "./plugin-config/[name].[ext]"
}
}
]
}
]
},
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true,
inline: true,
port: 3000,
// historyApiFallback: true,
hot: true
},
plugins: [
new ExtractTextPlugin(
{ filename: 'style.css'}
),
new CleanWebpackPlugin('dist', { watch: true,
}),
new HtmlWebpackPlugin({
inject: false,
hash: true,
template: './src/index.html',
}),
new WebpackMd5Hash(),
]
};
解决方案
在 webpack 4 中,只有真正的入口点是入口点,这意味着入口中没有供应商脚本、插件……。您不能glob
在这里使用,因为它会创建一个包含所有 js 文件的数组,并且只是server.js
您应用程序的真正入口点!
将 js 文件添加到您的 wp 项目并不意味着它将被编译,因为您不会在任何地方引用它,因此 wp 无法知道它是否需要它。WP 从入口点的依赖关系开始创建依赖关系图并创建捆绑包。
你server.js
是你的入口点,应该是这样的:
import "../stylesheets/style.scss";
import $ from 'jquery';
import "./clickable" // without import no recompile!
import "./hide"
import "./show"
console.log("his");
console.log("hello, world23");
您的入口点webpack.config.js
:
module.exports = {
entry: {
main: path.resolve(__dirname, "./src/javascripts/server.js")
},