DEV Community

Paul Loveridge
Paul Loveridge

Posted on

Webpack output based upon environment variable

My first dev.to post - I've been wondering what to write for a while. But recently had a problem at work and found what I thought was a nifty solution. So I thought I'd share and help out others and perhaps even be told what I'd done wrong.

For my day job I'm a developer on a mature Java webapp. (And when I say mature I mean it's old enough to remember the Christopher Eccleston as Doctor Who.)

So as part of this we've decided to start building a React based client project to replace our older parts of written with JSPs, JSTL and JQuery. I wanted the React code to be quickly editable and viewable during development app with as small a delay as possible.

To keep the react client seperate it's partitioned under {appname}/react so it doesnt interfere with any of the older client code.

I could get the project deployed as part of the webapp but to refresh anything when react source changed required a tomcat restart, which would be a cycle time of 45 to 60 seconds, plus I'd have to login again.

Not a good way to write UI code. What I needed was the compiled react app to get updated within the running tomcat as it changed (and I could use webpack's watch option to automate that).

The first issue was to know where to put it. Eclipse doesnt deploy to tomcat but runs tomcat with apps deployed somewhere in whatever tomcat integration plugin it's using. Fortunately you can change that by editing the server settings in Eclipse.

Eclipse webapps destination folder

The solution was the edit where Eclipse deployed the webapps (so I knew where it was) and have webpack build stright into the /react folder there.

My webpack.config.js looked like this:

output : {
    path :path.join(__dirname, "../.metadata/eclipse_wtp/wtpwebapps/app/react/dist")
},

But that wasnt ideal. It used a hardcoded output folder that was only applicable on my work machine, not any other developers and (more importantly) not for Jenkins.

The solution was to use an environment variable to specify where the output folder was and use a default if it wasnt set. I choose APP_REACT_DIR for my variable name .

Just ahead of my module exports I defined a new constant

const distFolder = process.env.APP_REACT_DIR ?
  path.join(__dirname, process.env.APP_REACT_DIR ) 
  : 'dist';

Then inside webpack.config.js the output config then looked like this:

output : {
    path : distFolder
}

Bingo! Now setting whenever webpack is run in watch mode the updates happen in seconds. It will deploy to APP_REACT_DIR if set, but if not to the project's dist folder.

Top comments (0)