Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove attributes from tags inside Vue components?

Tags:

I want to use data-test attributes (as suggested here), so when running tests I can reference tags using these attributes.

  <template>
    <div class="card-deck" data-test="container">content</div>
  </template>

The element will be found using:

document.querySelector('[data-test="container"]')
// and not using: document.querySelector('.card-deck')

But I don't want these data-test attributes to get to production, I need to remove them. How can I do that? (There are babel plugins that do that for react.)

Thanks!

like image 384
awho Avatar asked Dec 21 '17 16:12

awho


1 Answers

The solution (for a Nuxt.js project), provided by Linus Borg in this thread, is:

// nuxt.config.js
module.exports = {
  // ...
  build:   {
    // ...
    extend(config, ctx) {
      // ...
      const vueLoader = config.module.rules.find(rule => rule.loader === 'vue-loader')
      vueLoader.options.compilerModules = [{
        preTransformNode(astEl) {
          if (!ctx.dev) {
            const {attrsMap, attrsList} = astEl
            tagAttributesForTesting.forEach((attribute) => {
              if (attrsMap[attribute]) {
                delete attrsMap[attribute]
                const index = attrsList.findIndex(x => x.name === attribute)
                attrsList.splice(index, 1)
              }
            })
          }
          return astEl
        },
      }]
    }
  }
}

where tagAttributesForTesting is an array with all attributes to be removed, like: ["data-test", ":data-test", "v-bind:data-test"].

like image 109
awho Avatar answered Sep 20 '22 12:09

awho