我有一个脚本,它生成一个文件,称为auto.js。此文件包含一些动态生成的导入,正在VueJS项目中使用。
// auto.js
import { apple, strawberry, orange } from 'delicious-fruits';
import { carrot, cucumber, celery } from 'delicious-vegetables';在使用Webpacks dev服务器时,如果任何项目文件发生更改,我的目标是让这个脚本重新生成我的auto.js文件,然后将它包含在重新编译的项目中。
我已经把这个脚本变成了Webpack插件,通过这个插件,我正在收听watchRun 编译器钩子。根据它的描述,这似乎是一个理想的挂钩:
在触发新编译之后,但在实际开始编译之前,在监视模式下执行插件。
class AutoGenerate {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.hooks.watchRun.tap('AutoGenerate', () => {
generateFile()
})
}
}
function generateFile () {
// generate auto.js and write to disk
}我总是遇到无限循环的情况。我尝试通过使用各种生命周期事件(钩子)来解决这个问题,同时忽略了自动生成的文件。当然,通过忽略它,这些更改不包含在重新编译的项目中。
const webpack = require('webpack');
const AutoGenerate = require("./auto.plugin");
module.exports = {
configureWebpack: {
plugins: [
new webpack.WatchIgnorePlugin([/.*auto\.js/]),
new AutoGenerate()
]
}
}我还尝试过使用编译,并在编译中添加了一个新的资产。虽然进程不会出错,但生成的资产并不是最终编译的一部分。
// auto.plugin.js
class AutoGenerate {
static defaultOptions = {
outputFile: 'auto.js',
};
constructor(options = {}) {
this.options = { ...AutoGenerate.defaultOptions, ...options };
}
apply(compiler) {
compiler.hooks.thisCompilation.tap('AutoGenerate', (compilation) => {
const path = require("path")
const filePath = path.resolve(__dirname, `src/plugins/${this.options.outputFile}`)
const { RawSource } = require('webpack-sources')
const fileContent = new RawSource(generateFile())
compilation.emitAsset(
filePath,
fileContent
)
});
}
}
function generateFile() {
// generate file content & return as string
}
module.exports = { AutoGenerate };// vue.config.js
const AutoGenerate = require("./auto.plugin");
module.exports = {
configureWebpack: {
plugins: [
new AutoGenerate()
]
}
}如何触发自动生成该文件的逻辑,同时将此文件作为任何重新编译的一部分,同时避免无限循环?
发布于 2021-05-26 22:38:53
我未能找出直接解决上述问题的方法。但是,对于任何阅读的人来说,我都会发现这可以通过使用一个名为before-build-webpack的包来实现,特别是包括watch-run触发器。
// vue.config.js
const WebpackBeforeBuildPlugin = require('before-build-webpack')
module.exports = {
configureWebpack: {
plugins: [
new WebpackBeforeBuildPlugin(function(stats, callback) {
// ...
}, ['run', 'watch-run'])
]
}
}https://stackoverflow.com/questions/67641448
复制相似问题