How do I create a loader for webpack that exposes all sources through a function?

I would like to have a loader that collects all sources css

and allows me to get all the content in a function. Like this:

Webpack config

module: {
  loaders: [
    {test: /\.css$/, loader: 'my-loader'}
  ]
}

      

JS file A ( foo.js

)

import './foo.css';

      

JS file B ( bar.js

)

import './bar.css';

      

JS file C ( app.js

)

import './app.css';
import getAllCSSContents from 'my-loader';

const css = getAllCSSContents();

      

where getAllCSSContents

will return all CSS content from foo.css

, bar.css

andapp.css

+3


source to share


1 answer


This is a bit tricky because the loader you want to make needs to know about all the CSS modules before it can generate the code it needs to return, making it workable (loaders should be pure functions that transform a single input module).

You can achieve what you want using raw-loader

and require.context

:



// Load all CSS files in the current directory and descendants
const context = require.context('!raw-loader!./', true, /\.css$/);
const cssFiles = {};

for (let filename of context.keys()) {
  cssFiles[filename] = context(filename);
}

      

+1


source







All Articles