如何在Webpack钩子中打破循环

6
我正在使用nuxt.js项目,需要在每次webpack构建时运行一个shell脚本来处理更改的文件。
因此,我正在使用Webpack Hooks
我创建了自己的Webpack插件

/plugins/NamedExports.js

const pluginName = 'NamedExports'
const { exec } = require('child_process')

class NamedExports {
  apply(compiler) {
    compiler.hooks.beforeCompile.tap(pluginName, (params, callback) => {
      exec('sh plugins/shell.sh', (err, stdout, stderr) => {
        console.log(stdout)
        console.log(stderr)
      })
    })
  }
}

export default NamedExports

plugins/shell.js

parameters=$(ls components)
for item in ${parameters[*]}
do
    ls components/$item/ | grep -v index.js | sed 's#^\([^.]*\).*$#export { default as \1 } from "./&"#' > components/$item/index.js
done

echo "worked"

这个脚本是为了在组件目录中的每个文件夹中创建命名导出,例如。

components/atoms/ButtonStyled.vue components/atoms/BoxStyled.vue

然后它会生成 components/atoms/index.js

export { default as ButtonStyled } from "./ButtonStyled.vue"
export { default as BoxStyled } from "./BoxStyled.vue"

我在nuxt.config.nuxtwebpack.config.js中注册了我的插件。

import NamedExports from './plugins/NamedExports.js'

export default {
  // ... other config here ...
  build: {
    plugins: [
      // ... other plugins here ...
      new NamedExports()
    ],
  }
}

但是当我运行我的应用程序并更改任何文件时,服务器会提示已对components/atoms/index.js进行更改,然后进行新的构建,因此它会无限制地构建。
有人能帮我打破这个循环吗?
因为只要更改一个文件,就生成新的index.js而不是生成无限构建。
提前感谢。
2个回答

1

0

问题显然是新文件重新触发了构建。从概念上讲,有几种方法可以解决这个问题。

1)如果文件已更新,则不要输出新文件。您需要比较时间戳。这可能会很混乱。

2)编写一个加载器。匹配components/**/index.js,输出正确的JavaScript代码。确保无状态。即不要输出另一个文件,只需输出字符串。

然后在每个目录中放置带有注释的虚拟文件,说明它是由webpack插件自动生成的。

如果您的虚拟文件告诉webpack如何生成它,那就更好了。

https://webpack.js.org/contribute/writing-a-loader/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接