SharpCoder
SharpCoder

Reputation: 19183

Webpack - Setting path context for various assets and resources when bundle is created

I am working on reactjs application and bundling the application using webpack.

This is how I am setting path for css file in my index.html file.

  <link rel="stylesheet" href="/styles.css" media="screen" charset="utf-8">

When I run the command npm run dev locally, system run a web server on port 8080 and I can access the application. All this works fine.

When I deploy the application in different environment, due to certain policy, we need to host the application under a sub folder.

What it means is any resource which uses relative path in the application needs to be made aware of this change.

Assuming the subfolder name is TEST. In this case a resource which was available as http://localhost:8080/abc.png locally will now we available as http://localhost:8080/TEST/abc.png .

I am not sure what is the best way to handle such scenarios. What I am thinking is I will create a global variable call window_context and every resource which uses relative path will make use of this variable.

so to include styles.css not I will use

<link rel="stylesheet" href="{window_context}/styles.css" media="screen" charset="utf-8">

if I am running the application locally the variable will be empty and if I am using web pack to create a bundle, I will set window_context = '/TEST'.

How do I access the variable using webpack & assign it a value based on the command I am running.

So If I say npm run dev (which run the app locally and launches a web server) the window_context should be set as '' and if I run npm run build (which creates a bundle), it should set the window_context to '/TEST'

Upvotes: 0

Views: 1269

Answers (1)

Brendan Gannon
Brendan Gannon

Reputation: 2652

output.publicPath should be the right choice, yes. If you want it to change from one env to another, you should do separate builds for the two environments. If your webpack.config.js file exports an array of config objects instead of just one, webpack will automatically do a build for each object. So you can have an array of two (or more) build configs, where each has a different publicPath.

[Edit]: here's a very simple example of a webpack.config.js:

var buildConfigs = [];
module.exports = buildConfigs;

var envs = ['dev', 'production'];
envs.forEach(function(env) {
  var conf = {};
  conf.entry = './entry.js';
  conf.output = {};
  if (env === 'production') {
    conf.output.publicPath = '/DW';
  } else {
    conf.output.publicPath = '/';
  }

  buildConfigs.push(conf);
});

This exports an array where all of the config is shared between two builds, except the publicPath. Your real build config will of course be a lot bigger, but you can keep it clean by defining the various parts of the config separately as variables, or even in separate modules that you require from this file.

Upvotes: 2

Related Questions