From 8082c61f3f1ad14109a3eceeb8a2026b19933600 Mon Sep 17 00:00:00 2001 From: Hugo Alliaume Date: Thu, 15 Apr 2021 08:40:56 +0200 Subject: [PATCH] feat: add Encore.when() --- index.js | 23 +++++++++++++++++++++++ test/index.js | 16 ++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/index.js b/index.js index 143745f3..66e6b881 100644 --- a/index.js +++ b/index.js @@ -1596,6 +1596,29 @@ class Encore { return webpackConfig.isDevServer(); } + /** + * Use to conditionally configure or enable features only in when the first parameter results to "true". + * + * ``` + * Encore + * // passing a callback + * .when((Encore) => Encore.isProduction(), (Encore) => Encore.enableVersioning()) + * // passing a boolean + * .when(process.argv.includes('--analyze'), (Encore) => Encore.addPlugin(new BundleAnalyzerPlugin())) + * ``` + * + * @param {(function(Encore): boolean) | boolean} condition + * @param {function(Encore): void} callback + * @return {Encore} + */ + when(condition, callback) { + if (typeof condition === 'function' && condition(this) || typeof condition === 'boolean' && condition) { + callback(this); + } + + return this; + } + /** * Use this at the bottom of your webpack.config.js file: * diff --git a/test/index.js b/test/index.js index ba99ad7a..18858cfb 100644 --- a/test/index.js +++ b/test/index.js @@ -10,6 +10,7 @@ 'use strict'; const expect = require('chai').expect; +const sinon = require('sinon'); const api = require('../index'); const path = require('path'); @@ -454,6 +455,21 @@ describe('Public API', () => { }); + describe('when', () => { + it('should call or not callbacks depending of the conditions', () => { + api.configureRuntimeEnvironment('dev', {}, false); + + const spy = sinon.spy(); + api + .when((Encore) => Encore.isDev(), (Encore) => spy('is dev')) + .when((Encore) => Encore.isProduction(), (Encore) => spy('is production')) + .when(true, (Encore) => spy('true')); + expect(spy.calledWith('is dev'), 'callback for "is dev" should be called').to.be.true; + expect(spy.calledWith('is production'), 'callback for "is production" should NOT be called').to.be.false; + expect(spy.calledWith('true'), 'callback for "true" should be called').to.be.true; + }); + }); + describe('isRuntimeEnvironmentConfigured', () => { it('should return true if the runtime environment has been configured', () => {