Tokimon
Tokimon

Reputation: 4152

Webpack - Add asset to stats

I'm still kinda new to building Webpack plugins, so I have a question regarding how to properly add assets to the compilation.

I am building this plugin: rebabel-webpack-plugin
That, in all its simplicity, takes the compiled files and recompiles them again with babel to transpile them into fx ES 5 compatible files (I know... it seems weird... The why is in the project's readme).

This actually works pretty well, but my assets are not showing up in the Stats part of webpack (eg. compiler.getStats())

I am adding my recompiled assets to the compilation.assets list, but only my initial entry files and a dynamic named chunk shows up in the stats object.

So how do I make my recompiled assets show up in webpack's stats section?

Upvotes: 0

Views: 337

Answers (1)

Tokimon
Tokimon

Reputation: 4152

So after some digging around I think I found a solution to my problem. It seems that I needed to add my newly created assets as chunks as well and change the names of the file references in there.

So the following code seems to solve the problem:

function addPrefixToFile(prefix, file) {
  return file.replace(/(^|[/\\])([^/\\]+)$/, `$1${prefix}$2`);
}

const files = chunks.reduce((arr, chunk) => {
  if(!chunk.rendered) { return arr; }

  // Create chunk copy
  const copy = Object.assign(Object.create(chunk), {
    name: chunk.name ? `${prefix}${chunk.name}` : chunk.name,
    files: (chunk.files || []).map((file) => addPrefixToFile(file)),
    parents: chunk.parents.map(
      (parent) => Object.assign({}, parent, {
        files: (parent.files || []).map((file) => addPrefixToFile(file))
      })
    )
  });

  chunkCopies.push(copy);
}, []);

// ... further down the line ...
chunks.push(...chunkCopies);

To me it seems a bit hacky so I was wondering if there is a better way of doing this. But well... it works.

Upvotes: 0

Related Questions