Sunday, November 21, 2021

Hacking in to webpack build process

With API Manager, we have a requirement to allow users to keep a separate source folder for each web application. To describe the requirement a bit more, we have a folder structure as follows.




















We are sending updates to the source folder after releasing the product. If a developer customized the content in the source folder, it will be rewritten by the new updates. So for them to maintain the code separately we wanted to implement a file overriding mechanism. Our goal was to allow users to copy the file into a different folder on the same level as the source folder and do the customization logic there. Example.






















The files in the overrides folder should take president over the files in the source folder. To achieve this we use a Webpack loader. A Webpack loader can be used to tap into the Webpack build process. 

 
   test: /\.(js|jsx)$/, 
   exclude: /node_modules/, 
   use: [ 
    { 
      loader: path.resolve('loader.js'), 
    }, 
   ], 
},  

https://github.com/wso2/apim-apps/blob/v9.0.389/portals/publisher/src/main/webapp/webpack.config.js#L139

Now, all we need to do is create a new file at the same level as weback.config.js and add our logic. We get the list of files and the source content as input params. 

  module.exports = function (source, map) 
 ..... 
 // Do your magic 
 this.callback(null, newSource, map); 

Loader source https://github.com/wso2/apim-apps/blob/v9.0.389/portals/publisher/src/main/webapp/loader.js