Skip to content

Instantly share code, notes, and snippets.

@Leedehai
Last active November 21, 2019 20:47
Show Gist options
  • Save Leedehai/fc1a548f6a5443df3ad09fa6feece95a to your computer and use it in GitHub Desktop.
Save Leedehai/fc1a548f6a5443df3ad09fa6feece95a to your computer and use it in GitHub Desktop.
to-string-loader for Webpack, with comments removed.
/**
* Copyright (c) 2019 The contributors of https://github.com/gajus/to-string-loader
* License under the BSD-3-Clause License.
* Copyright (c) 2019 Leedehai. All rights reserved.
* Licensed under the MIT License. For details, refer to LICENSE.txt
* under the project root.
*
* File: code-to-string-loader.js
* -----------------------------------------
* A fork of to-string-loader (version 1.1.6) for Webpack:
* npm: https://www.npmjs.com/package/to-string-loader
* source: https://github.com/gajus/to-string-loader
* I only added the 'processString' part.
*/
/* eslint-disable import/no-commonjs */
'use strict';
const loaderUtils = require('loader-utils');
/**
* @see https://webpack.github.io/docs/loaders.html
*/
module.exports = function() {};
/**
* @see https://webpack.github.io/docs/loaders.html#pitching-loader
* @param {*} remainingRequest
* @return {string}
*/
module.exports.pitch = function(remainingRequest) {
if (this.cacheable) {
this.cacheable();
}
return `
var result = require(${loaderUtils.stringifyRequest(this, '!!' + remainingRequest)});
const processString = str => {
const removeComments = str => str.replace(/\\/\\*[\\s\\S]*?\\*\\/(\\s)*|([^\\:]|^)\\/\\/.*$/gm, '');
const compressBlanks = str => str.replace(/( )+/g, ' '); // just compress, not remove
return compressBlanks(removeComments(str));
}
if (typeof result === "string") {
module.exports = processString(result);
} else {
module.exports = processString(result.toString());
}
`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment