Skip to content

Commit

Permalink
feat: add Encore.when()
Browse files Browse the repository at this point in the history
  • Loading branch information
Kocal authored and weaverryan committed Apr 22, 2021
1 parent a7a6a24 commit 8082c61
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
23 changes: 23 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:
*
Expand Down
16 changes: 16 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
'use strict';

const expect = require('chai').expect;
const sinon = require('sinon');
const api = require('../index');
const path = require('path');

Expand Down Expand Up @@ -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', () => {
Expand Down

0 comments on commit 8082c61

Please sign in to comment.