I have a very simple front end, but I wanted to be able to swap out instances of my API URLs in TypeScript depending which environment I am working in or building for. So far they are all ‘http://127.0.0.1:8000/’, but when I deploy, I didn’t want to have to remember to set a URL for prod or staging etc.

I was hoping to find a way to do this with just TypeScript, but unfortunately, I was unable to find a good way to do this with just the TypeScript compiler for static files. I’m not a big fan of the complexity that webpack adds, but I’ve noticed it also minifies and obfuscates my javascript, which is a nice bonus. If you know of a good way to do this with the TypeScript compiler alone, please let me know!

I tried a few different methods, but using webpack and splitting my config into development and production worked. Otherwise, I mostly just followed the installation instructions for webpack including installing locally. I tried installing globally based on other tutorials, but I ran into a bunch of issues doing that.

With this setup, I run ‘npm run build:test’ or ‘npm run build:prod’ depending if I am working locally or building for production. Those commands are mapped in package.json:

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build:test": "webpack --config webpack.dev.js --watch ",
    "build:prod": "webpack --config webpack.prod.js"
  },

I added –watch on test so that when I’m developing in VSCode, I can just leave it running and it’ll update whenever I save a file. If I want to run that manually I have to run ‘node_modules/.bin/webpack –config webpack.dev.js –watch’ because I installed webpack locally.

When I first got this set up, I realized it was only outputting a single Javascript file because I didn’t understand how ‘entry’ and ‘output’ worked in the webpack config file (see code below). Now I define each entry JS file for each page (they both have an import for my config with the IP addresses) with a name. Under ‘output’ [name].js corresponds with each ‘entry’. So my output ends up in the dist/ folder and the two files are named ‘login.js’ and ‘purchase.js’ based on the two fields in the ‘entry’ object. Any files added to ‘entry’ will produce a corresponding output Javascript file.

I also missed something in the instructions for Typescript when I was initially setting this up that lead to a long hunt for why it wasn’t including my config.ts file (the error messages were not great). Don’t forget the ‘resolve’ field below or webpack will get confused when trying to import any file with a .ts extension referenced in another file.

webpack.common.js

const path = require('path');

module.exports = {
  entry: {    
    login: './src/login.ts',
    purchase: './src/purchase.ts'   
  },
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ]
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist')
  }
};

webpack.dev.js

const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: 'development'
});

webpack.prod.js

const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: production
});

config.ts, which changes the API URL based on what environment we are targeting (based on: https://basarat.gitbooks.io/typescript/content/docs/tips/build-toggles.html)

/**
 * This interface makes sure we don't miss adding a property to both `prod` and `test`
 */
interface Config {
    baseAPIURL: string;
}

/**
 * We only export a single thing. The config.
 */
export let config: Config;

/**
 * `process.env.NODE_ENV` definition is driven from webpack
 *
 * The whole `else` block will be removed in the emitted JavaScript
 *  for a production build
 */
if (process.env.NODE_ENV === 'production') {
    config = {
        baseAPIURL: 'http://127.0.0.1:8000/'
    }
    console.log('Running in prod');
} else // if (process.env.NODE_ENV === 'development') 
{
    config = {
        baseAPIURL: 'http://127.0.0.1:8000/'
    }
    console.log('Running in test');
}

And finally this is how you import the config into any of the Javascript files.

import {config} from './config'

From that gitbooks link, I tried to just set up my build command (without breaking up the webpack.config.js into common/dev/prod) but this did not work for me:

 "scripts": {
"build:test": "webpack -p --define process.env.NODE_ENV='\"dev\"' --config ./webpack.config.js"
  },

Neither did DefinePlugin from the weback docs. I think DefinePlugin failed because it is trying to use global webpack which isn’t installed. Or maybe it’s something else. But the error looked similar to when I try to run ‘webpack’ instead of ‘node_modules/.bin/webpack’.