Text replacement on a copied file with webpack

Viewed 2852

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.

2 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);
  },
}])

Try with xml-webpack-plugin. I hope this help you.

webpack.config.js

var XMLWebpackPlugin = require('xml-webpack-plugin')

var xmlFiles = [
    {
        template: path.join(__dirname, 'browserconfig.ejs'),
        filename: 'browserconfig.xml',
        data: {
            square70x70logo: 'images/icon70.png',
            square150x150logo: 'images/icon150.png',
            wide310x150logo: 'images/icon310x150.png',
            square310x310logo: 'images/icon310.png',
            tileColor: '#ffffff'
        }
    }
]

browserconfig.ejs

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
    <msapplication>
        <tile>
            <square70x70logo src="<%= square70x70logo %>"/>
            <square150x150logo src="<%= square150x150logo %>"/>
            <wide310x150logo src="<%= wide310x150logo %>"/>
            <square310x310logo src="<%= square310x310logo %>"/>
            <TileColor><%= tileColor %></TileColor>
        </tile>
    </msapplication>
</browserconfig>
Related