Webpack plugin to modify a file before and after compilation

7.7k Views Asked by At

I'm trying to build a webpack plugin that does a simple thing, replace a string in a file before webpack compiles everything, and place that string back after the compilation.

A configuration would look like this:

{
   files: ['myFile.js'],
   replace: 'myString'
}

Basically I don't want webpack to see myString, so I replace it with some unique string and then put myString back, after webpack compiles everything. The plugins/loaders named in this answer don't fit my use case.

I think a loader is not needed, because I know what files have to change so I don't need to analyze each file.

I've read the doc about plugins but I'm still kinda lost and probably doing a very inefficient plugin. Maybe someone with experience with plugins can guide me.

1

There are 1 best solutions below

1
On

I didn't see string-replace-webpack-plugin in the linked answer. We use this to replace strings that need to change based on which environment they are deployed to. You can use the test key to limit to the filename that contains the string you want to change.

Example from their README:

loaders: [
     // configure replacements for file patterns 
     { 
        test: /index.html$/,
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: /<!-- @secret (\w*?) -->/ig,
                    replacement: function (match, p1, offset, string) {
                        return secrets.web[p1];
                    }
                }
            ]})
        }
]

We do something simple like:

{
    pattern: /_GOOGLE_ID_//ig,
    replacement: function (match, p1, offset, string) {
        return 'my-actual-google-id-for-this-env';
    }
}