【发布时间】:2019-11-17 08:15:52
【问题描述】:
我有一个带有 nuxt.js / Vue 的应用程序。
我创建了一个 Webpack 插件,以便随着每个文件的更改,在某个目录中生成一个 index.js。
问题是当index.js 生成时,Webpack 将其识别为新的更改并再次构建,因此它停留在那个无限循环中......
为了检测变化,我使用webpack hooks
compiler.hooks.beforeCompile.tapAsync('MyPlugin', (params, callback) => {
// script to generate an index.js in a given directory
});
如何防止index.js 触发新构建?
更新问题以便更好地理解
我正在开发一个使用 vue.js 制作的应用程序 | nuxt.js 和这个组件结构
├── components
│ ├── quarks
│ │ └── ...
│ ├── bosons
│ │ └── GridLayout.vue
│ │ └── ...
│ ├── atoms
│ │ └── ButtonStyle.vue
│ │ └── InputStyle.vue
│ │ └── ...
│ ├── molecules
│ │ └── ...
│ ├── organisms
│ │ └── ...
│ ├── templates
│ │ └── ...
└─────
我需要进行命名和分组导入,如下所示:
import { ButtonStyle, InputStyle } from '@/components/atoms/'
但要解决这个问题,我需要在每个文件夹中都有一个 index.js,逐个导出组件,例如
├── components
│ ├── atoms
│ │ └── ButtonStyle.vue
│ │ └── InputStyle.vue
│ │ └── index.js
└─────
在index.js
export { default as ButtonStyled } from './ButtonStyled.vue'
export { default as InputStyle } from './InputStyle.vue'
但是手动完成这项工作可能是一项非常令人厌烦的任务。每次创建、删除、重命名组件时,都必须更新各自文件夹的 index.js。
所以我开始开发解决方案
在nuxt.config.js
import NamedExports from './plugins/NamedExports.js'
export default {
// ... other config here ...
build: {
plugins: [
new NamedExports()
],
}
}
在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.sh
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
但每当插件创建index.js 时,就会触发新的构建
【问题讨论】:
标签: javascript node.js webpack nuxt.js