6

I'm working with a project nuxt.js, I need to run a shell script on every changed file, that is, every webpack build.

so I'm using the Webpack Hooks

I created my Webpack Plugin

/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"

this script is to make named exports within each folder in the component directory, example

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

then it is generated components/atoms/index.js

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

I registered my Plugin in nuxt.config.nuxt or webpack.config.js

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

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

but when I run my app and change any file, the server says that a change has been made to components/atoms/index.js and then a new build is done, so it gets infinite build.

Can someone help me break this loop?

for when to change a file, simply generate new index.js and not generate infinite builds

thanks in advance

0

2 Answers 2

1

I created a library and solved my problems, below is the link:

Weback Plugin - named-exports

0

The problem is obviously new files retriggering a build. Conceptually, there are a few ways of going about this.

1) if the files are updated, don't output new files. You need to compare timestamps for this. It's probably going to be messy.

2) write a loader. Match components/**/index.js, output the correct javascript for it. Ensure stateless. I.e. Don't output another file, just a string.

Then put dummy files in each directory with a comment that it's auto-generated by a webpack plugin.

Even better if your dummy file tells webpack how to generate it.

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.