Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text replacement on a copied file with webpack

I have a build.config.xml that has a couple of strings in it like $FABRIC_API_KEY. I want to replace this with process.env.FABRIC_API_KEY in a new file config.xml (build.config.xml should remain the same). I have tried using CopyWebpackPlugin, but I can't seem to get this to do anything.

var CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  ...    
  resolve: {
    extensions: ['.ts', '.js', '.json', '.xml'],
    ...

  plugins: [
    ionicWebpackFactory.getIonicEnvironmentPlugin(),
    new CopyWebpackPlugin([{
      from: 'build.config.xml',
      to: 'config.xml',
      transform: function (content) {
        content = content
          .replace('$FABRIC_API_SECRET', process.env.FABRIC_API_SECRET)
          .replace('$FABRIC_API_KEY', process.env.FABRIC_API_KEY);

        return content;
      },
    }]),
  ],
};

The file does other things (builds ionic) and everything else works as expected. There are no errors or anything, and config.xml does not get created.

What can I do to copy a file and replace strings in it? I am open to using another plugin.

like image 275
Explosion Pills Avatar asked Jul 31 '17 22:07

Explosion Pills


1 Answers

Probably many things have changed since the OP, but the transform function of the copy-webpack-plugin does allow to modify the file contents. The content argument passed to the function is a buffer though, hence a simple string replacement can be achieved like this (notice the call to toString()):

new CopyWebpackPlugin([{
  from: 'build.config.xml',
  to: 'config.xml',
  transform(content) {
    return content
      .toString()
      .replace('$FABRIC_API_SECRET', process.env.FABRIC_API_SECRET)
      .replace('$FABRIC_API_KEY', process.env.FABRIC_API_KEY);
  },
}])
like image 127
dilico Avatar answered Nov 30 '22 12:11

dilico