Skip to content

Add Encore.configureRuntimeEnvironment() method to the public API #115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 111 additions & 19 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,27 @@ const WebpackConfig = require('./lib/WebpackConfig');
const configGenerator = require('./lib/config-generator');
const validator = require('./lib/config/validator');
const PrettyError = require('pretty-error');
const runtimeConfig = require('./lib/context').runtimeConfig;
const logger = require('./lib/logger');
const parseRuntime = require('./lib/config/parse-runtime');

// at this time, the encore executable should have set the runtimeConfig
if (!runtimeConfig) {
throw new Error('Are you trying to require index.js directly?');
let webpackConfig = null;
let runtimeConfig = require('./lib/context').runtimeConfig;

function initializeWebpackConfig() {
if (runtimeConfig.verbose) {
logger.verbose();
}

webpackConfig = new WebpackConfig(runtimeConfig);
}

let webpackConfig = new WebpackConfig(runtimeConfig);
if (runtimeConfig.verbose) {
logger.verbose();
// If runtimeConfig is already set webpackConfig can directly
// be initialized here.
if (runtimeConfig) {
initializeWebpackConfig();
}

module.exports = {
const publicApi = {
/**
* The directory where your files should be output.
*
Expand Down Expand Up @@ -431,17 +438,9 @@ module.exports = {
* @returns {*}
*/
getWebpackConfig() {
try {
validator(webpackConfig);

return configGenerator(webpackConfig);
} catch (error) {
// prettifies errors thrown by our library
const pe = new PrettyError();
validator(webpackConfig);

console.log(pe.render(error));
process.exit(1); // eslint-disable-line
}
return configGenerator(webpackConfig);
},

/**
Expand All @@ -454,5 +453,98 @@ module.exports = {
*/
reset() {
webpackConfig = new WebpackConfig(runtimeConfig);
}
},

/**
* Initialize the runtime environment.
*
* This can be used to configure the Encore runtime if you're
* using Encore without executing the "./node_module/.bin/encore"
* utility (e.g. with karma-webpack).
*
* Encore.configureRuntimeEnvironment(
* // Environment to use (dev, dev-server, production)
* 'dev-server',
*
* // Same options you would use with the
* // CLI utility with their name in
* // camelCase.
* {
* https: true,
* keepPublicPath: true
* }
* )
*
* Be aware than using this method will also reset the current
* webpack configuration.
*
* @param {string} environment
* @param {object} options
* @returns {exports}
*/
configureRuntimeEnvironment(environment, options = {}) {
runtimeConfig = parseRuntime(
Object.assign(
{},
require('yargs/yargs')([environment]).argv,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand this. Is there a need to continue to read the command line options? The command line options could be totally different (since there is a different executable being run).

I see that parseRuntime() looks for argv._[0] for the environment/command. Is that what you're trying to supply here? If so, I think we could set that manually - e.g. options._ = [environment]. Or, we could re-work parse-runtime.js so that the argv._[0] is actually done in encore.js and parse-runtime looked like function(command, options, cwd) {.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added that part to make sure that the first parameter passed to parseRuntime had the same structure than the one usually supplied by yargs, it doesn't actually keep reading the CLI options since we provide a fake process.argv (see https://github.com/yargs/yargs/blob/master/docs/api.md#api).

I did options._ = [environment] at first but switched to calling the API after realizing that yargs adds other things to the argv array that may be used later by parseRuntime (e.g.: $0)

options
),
process.cwd()
);

initializeWebpackConfig();

return this;
},

/**
* Clear the runtime environment.
*
* Be aware than using this method will also reset the
* current webpack configuration.
*
* @returns {void}
*/
clearRuntimeEnvironment() {
runtimeConfig = null;
webpackConfig = null;
},
};

// Proxy the API in order to prevent calls to most of its methods
// if the webpackConfig object hasn't been initialized yet.
const publicApiProxy = new Proxy(publicApi, {
get: (target, prop) => {
if (typeof target[prop] === 'function') {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It shouldn't be possible, but what about the else of this function?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, I missed that part, I added a return target[prop] just in case.

// These methods of the public API can be called even if the
// webpackConfig object hasn't been initialized yet.
const safeMethods = [
'configureRuntimeEnvironment',
'clearRuntimeEnvironment',
];

if (!webpackConfig && (safeMethods.indexOf(prop) === -1)) {
throw new Error(`Encore.${prop}() cannot be called yet because the runtime environment doesn't appear to be configured. Make sure you're using the encore executable or call Encore.configureRuntimeEnvironment() first if you're purposely not calling Encore directly.`);
}

// Either a safe method has been called or the webpackConfig
// object is already available. In this case act as a passthrough.
return (...parameters) => {
try {
const res = target[prop](...parameters);
return (res === target) ? publicApiProxy : res;
} catch (error) {
// prettifies errors thrown by our library
const pe = new PrettyError();

console.log(pe.render(error));
process.exit(1); // eslint-disable-line
}
};
}

return target[prop];
}
});

module.exports = publicApiProxy;
27 changes: 26 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@
'use strict';

const expect = require('chai').expect;
require('../lib/context').runtimeConfig = {};
const api = require('../index');

describe('Public API', () => {
beforeEach(() => {
api.configureRuntimeEnvironment('dev');
});

describe('setOutputPath', () => {

Expand Down Expand Up @@ -203,4 +205,27 @@ describe('Public API', () => {
});

});

describe('configureRuntimeEnvironment', () => {

it('should return the API object', () => {
const returnedValue = api.configureRuntimeEnvironment('dev');
expect(returnedValue).to.equal(api);
});

});

describe('Runtime environment proxy', () => {
beforeEach(() => {
api.clearRuntimeEnvironment();
});

it('safe methods should be callable even if the runtime environment has not been configured', () => {
expect(() => api.clearRuntimeEnvironment()).to.not.throw();
});

it('unsafe methods should NOT be callable if the runtime environment has not been configured', () => {
expect(() => api.setOutputPath('/')).to.throw('Encore.setOutputPath() cannot be called yet');
});
});
});