jlengstorf / learn-rollup

This is an example project to accompany a tutorial on using Rollup.
https://code.lengstorf.com/learn-rollup-js/
ISC License
191 stars 61 forks source link

Replace / use specific file based on ENV condition #14

Closed dnmd closed 7 years ago

dnmd commented 7 years ago

First off, excellent tutorial on rollup, many thanks!

Quick question, since we are able to replace variables with actual values on an ENV condition I was (hoping) and wondering if the same holds true for files? Say we have two config files with equal properties, and based on the ENV condition, either the /config/environment.dev.ts or the /config/environment.prod.ts replaces the content in the /src/dist/environment.ts file. Any thoughts?

Redundant example:

├── /src/dist/environment.ts (stub, where either the content of {dev} or {prod} is used)

import { environment } from './src/dist/environment';

├── /config/environment.dev.ts

export const environment = {  
  production: false,
  apiUrl : ...,
};

├── /config/environment.prod.ts

export const environment = {  
  production: true,
  apiUrl: ...,
};

The Angular 2 CLI uses the approach described above, the example I use originates here: http://tattoocoder.com/angular-cli-using-the-environment-option/

jlengstorf commented 7 years ago

I haven't tested this, but I believe you could do something like this:

import { environment } from ENV_FILE;

And in the replace config:

ENV_FILE: JSON.stringify(process.env.NODE_ENV === 'production' ? 'env.prod.js' || 'env.dev.js'),

That might need tweaking, but since replacement is done during bundling, not at runtime, this ought to work.

dnmd commented 7 years ago

Sorry for the late response I got a bit swamped. When using TypeScript, the import { environment } from ENV_FILE statement throws an error (though it does compile of course) and you loose your intellisense. So to 'fix' that I used the last part of the path as a key. So far things work like a charm. Thanks again for your input and the great work on putting the tutorial together.

var isProd = process.env.NODE_ENV === 'production';
...
    replace({
      exclude: 'node_modules/**',
      //use the /config/environment-dev as the default import(!), no stub needed.
      '/config/environment-dev' : ( isProd ? '/config/environment-prod' : '/config/environment-dev'),
    })

This replaces any import (including deeper nested references) e.g. ../../.../config/environment-dev, with the proper path.