DEV Community

Kinga
Kinga

Posted on • Updated on

SPFx App Configuration, dev vs prod

The Read and manipulate SPFx configuration values in your code like a boss by Sergei Sergeev is a very good start for setting different configurations for different environments.

In the meantime however, the cross-env is in a maintenance mode, and at the same time we got some other tools we can use.

Building on top of the Advanced section of Sergei's article, I did the following changes to make things work with a minimum effort:

npm install webpack-merge --save-dev
Enter fullscreen mode Exit fullscreen mode
gulpfile.js
'use strict';

const build = require('@microsoft/sp-build-web');
const webpack = require('webpack');
const { merge } = require('webpack-merge'); //<--NEW
const argv = build.rig.getYargs().argv; //<--NEW

build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);

var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
    var result = getTasks.call(build.rig);
    result.set('serve', result.get('serve-deprecated'));

    return result;
};

//NEW
build.configureWebpack.setConfig({
    additionalConfiguration: function (config) {
        console.log(argv);
        let defineOptions;

        if (argv.production) {
            console.log('***********    Applying production settings to webpack *********************');
            // specify production keys here
            defineOptions = {
                'apiUrl': JSON.stringify('https://production_Url')
            }
        }
        else { 
            console.log('***********    Applying development settings to webpack *********************');
            defineOptions = {
                'apiUrl': JSON.stringify('https://dev_Url')
            }
        }

        return merge(config, {
            plugins: [
                new webpack.DefinePlugin(defineOptions)
            ]
        });
    }
});

build.initialize(require('gulp'));

Enter fullscreen mode Exit fullscreen mode

Have you noticed the const argv = build.rig.getYargs().argv;? I spotted it in another of Sergei's articles, and immediately used it to replace Yargs.

From this moment on, when calling gulp commands, the console.log(argv); command will print a list of available arguments. No changes to package.json required.

So for example:

  • gulp serve --nobrowser: production: false
  • gulp bundle: production: false
  • gulp bundle --ship: production: true

Top comments (0)