繁体   English   中英

Webpack:无限循环和自动生成的文件

[英]Webpack: Infinite watch loop and auto-generated files

我有一个生成文件的脚本,称之为auto.js 该文件包含一些动态生成的导入,并在 VueJS 项目中使用。

// auto.js

import { apple, strawberry, orange } from 'delicious-fruits';
import { carrot, cucumber, celery  } from 'delicious-vegetables';

在使用 Webpacks dev server时,如果任何项目文件发生更改,我的目标是让此脚本重新生成我的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()
    ]
  }
}

如何触发自动生成此文件的逻辑,同时将此文件作为任何重新编译的一部分包含在内,同时避免无限循环?

我无法确定上述问题的直接解决方案。 但是,对于任何阅读的人,我发现这可以通过使用名为before-build-webpack的 package 来实现,特别是通过包含watch-run触发器。

// vue.config.js

const WebpackBeforeBuildPlugin = require('before-build-webpack')

module.exports = {
  configureWebpack: {
    plugins: [
      new WebpackBeforeBuildPlugin(function(stats, callback) {
        // ...
      }, ['run', 'watch-run'])
    ]
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM