template-comment-loader.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /* eslint-env node */
  6. /*
  7. * Matches `// @if param // someCode` and evaluates the `option.param`.
  8. * If the param is evaluated to true, then uncomments the code.
  9. *
  10. * Note: Use this only for conditional imports. Otherwise use the webpack define plugin.
  11. */
  12. module.exports = function templateCommentLoader( source, map ) {
  13. source = source.replace( /\/\/ @if (!?[\w]+) \/\/(.+)/g, ( match, option, body ) => {
  14. // this.query comes from the webpack loader config.
  15. // Missing param in webpack loader config
  16. if ( !( option in this.query ) ) {
  17. return match;
  18. }
  19. const optionValue = this.query[ option ];
  20. // Do nothing when the option is falsy
  21. if ( !optionValue ) {
  22. return match;
  23. }
  24. // Replace the option in body with evaluated value.
  25. body = body.replace( new RegExp( option, 'g' ), this.query[ option ] );
  26. // Uncomment the following code otherwise.
  27. return `/* @if ${ option } */ ${ body }`;
  28. } );
  29. this.callback( null, source, map );
  30. };