Alex Radzivanovich
Alex Radzivanovich

Reputation: 354

Configure webpack to use custom require function

Is there any way to use custom require functions in webpack? So that instead of the standard ways to require a module

const styles = require("styles.css");
import styles from "styles.css";

I could write something like this

const styles = loadStyles("styles.css");

where loadStyles is a non-existing function but webpack would handle it in the same way as require.

This would be super-handy for running unit tests in node. For obvious reasons node cannot load a CSS or any other resource file with require as require is only for javascript modules. But it's pretty straightforward to mock a custom global function just for unit tests:

function loadStyles() { return "fake styles"; }

Long story short, I want to be able to tell webpack that loadStyles (or any other function) is the new require.

Upvotes: 0

Views: 972

Answers (1)

Felix
Felix

Reputation: 2691

No you can't - not without using loaders. Resolve only allows you to change the resolvement of pathes, not the loading by itself which means you can't replace/change the loaded content.

You can use Babel which allows skipping such imports. For React, there even exists a whole package for doing this: Babel-Plugin-React-CSS-Modules. This package allows including and resolving stylenames but keep the stylesheet separate of your script while testing/server side rendering.

If you're using Jest, it has a separate section on Handling Static Assets.


In general it depends on what you want to achieve. Many frameworks - or webpack/babel configurations at least - depend on imported style names (often hashed or something like that). This means you need the resolved class names of your stylesheets inside your scripts. Otherwise you won't be able to run conditions and other algorithms on them.

Babel and other applications/libraries allow you exactly that. They resolve your scss or css stylesheets by using import or require and look which classes are inside the stylesheet to map it into an object inside javascript. They don't pay attention to the stylesheets afterwards. This makes it perfect for tests and server side rendering as classes are resolved but handled by a different webpack loader.

There is no further need of a separate loadStyles function, which might do exactly that, except if you load styles from remote. To my knowledge, webpack doesn't support this at the moment (but loaders might help out here, too).

If you really want to do a lot of non common changes to your stylesheets, stick to require, write your own loader for it and activate/deactivate the loader based on an ENV parameter (e.g. production | test | development).

Upvotes: 1

Related Questions