Skip to content

Instantly share code, notes, and snippets.

@developit
Last active August 12, 2019 21:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developit/5f4b44ff3d0fb326084d25a975d3c747 to your computer and use it in GitHub Desktop.
Save developit/5f4b44ff3d0fb326084d25a975d3c747 to your computer and use it in GitHub Desktop.

inline-loader for webpack

Point this loader at an empty file, and it'll let you supply fake contents for that file.

import one from 'inline-loader?filenam=one.js&code=export default 1!./empty.js';

console.log(one)  // 1

You'll find this is most useful from the context of other plugins/loaders.

Example

Here's an example implementation of "HTML Modules", where an imported HTML file is parsed and its components broken out into virtual dependencies:

// example: html-module-loader.js
const DOMParser = require('jsdom')().window.DOMParser;
module.exports = function(code) {
  const doc = new DOMParser().parseFromString(code, 'text/html');
  const template = (doc.querySelector('template') || {}).innerHTML;
  const script = (doc.querySelector('script') || {}).textContent;
  const style = (doc.querySelector('style') || {}).textContent;
  return `
    import.meta.html = require('inline-loader?${JSON.stringify({
      code: template,
      filename: this.request + '.html'
    })}!${__dirname}/empty.html');

    import.meta.style = require('inline-loader?${JSON.stringify({
      code: template,
      filename: this.request + '.css'
    })}!${__dirname}/empty.css');

    ${script}
  `;
};
import loaderUtils from 'loader-utils';
module.exports = function(source, map, data) {
let { code, filename, cacheable } = loaderUtils.getOptions(this);
if (cacheable===false) this.cacheable(false);
this.resourcePath = filename;
return code;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment