从 Node.js 中运行 Webpack Watch
提供内容的 Node.js 服务器, express-static 编译您的内容, Webpack 则不必同时运行两者 npm run dev
和 webpack --watch
。您的 npm run dev
脚本可以运行 webpack --watch
对你来说,不需要 CLI,使用 Webpack 的 Node API 。
这是一个在 Node.js 脚本中导入 Webpack 并观察文件以进行更改的示例。 您可以将 webpack 配置 给 webpack()
功能如下:
const webpack = require('webpack');
// Defining the webpack config inline, but you can replace this
// with `require('./webpack.config.js')`
const config = {
mode: 'development',
entry: `${__dirname}/example/app.js`,
output: {
path: `${__dirname}/example`,
filename: 'app.min.js'
}
};
const compiler = webpack(config);
const watcher = compiler.watch({}, function(err) {
// Gets called every time Webpack finishes recompiling.
});
fs.writeFileSync(`${__dirname}/example/app.js`,
'module.exports = \'Hello, World\';');
由于 Node.js 的事件循环,您不必显式创建新线程。 您的 Node 进程既可以是 HTTP 服务器,也可以是 Webpack 编译器。 下面是一个 Node.js 脚本的示例:
const app = require('express')();
const webpack = require('webpack');
app.use(require('express-static')(`${__dirname}/example`));
const server = await app.listen(3000);
const config = {
mode: 'development',
entry: `${__dirname}/example/app.js`,
output: {
path: `${__dirname}/example`,
filename: 'app.min.js'
}
};
const compiler = webpack(config);
const watcher = compiler.watch({}, function(err) {
// Gets called every time Webpack finishes recompiling.
});
fs.writeFileSync(`${__dirname}/example/app.js`,
'module.exports = \'Hello, World\';');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: 在 Vue 中定义模板的 3 种方法
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论