2

I need to import the compiled CSS code as string from ".styl" (Stylus pre-processor) files.

From the viewpoint of logic:

  1. First we need to pre-process the styles. It's exprected that stylus-loader will do it with stylus pre-precessor.
  2. Next we need the raw css code. I suppose the raw-loader will not be enough because what stylus-loader return is not a string.

Below code:

import styles from "!raw-loader!stylus-loader?@Assets/Styles/Typography/ArticleFormatting.styl";

will return the stringified code looks like JavaScript:

var loaderUtils = require('loader-utils');
var stylus = require('stylus');
var path = require('path');
var fs = require('fs');
var when = require('when');
var whenNodefn = require('when/node/function');
var cloneDeep = require('lodash.clonedeep');

// ...

Just

import styles from "!stylus-loader?@Assets/Styles/Typography/ArticleFormatting.styl";

will cause the error:

Module parse failed: Unexpected token (1:0)                                                             friendly-errors 13:26:25  
File was processed with these loaders:
 * ./node_modules/stylus-loader/index.js
You may need an additional loader to handle the result of these loaders.
> .ArticleFormatting h2 {
|   padding: 5px;
|   font-weight: bold;

CSS-loader with Stylus-loader:

import styles from "!raw-loader!stylus-loader!@Assets/Styles/Typography/ArticleFormatting.styl";

imports the array like this:

[                                                                                                                                                                                                                                                          15:13:30
  [
    './node_modules/css-loader/dist/cjs.js!./node_modules/stylus-loader/index.js!./Assets/Styles/Typography/ArticleFormatting.styl',
    '',
    '',
    {
      version: 3,
      sources: [],
      names: [],
      mappings: '',
      sourceRoot: ''
    }
  ],
  toString: [Function: toString],
  i: 
}
Takeshi Tokugawa YD
  • 670
  • 5
  • 40
  • 124

1 Answers1

2

General idea is that you can access the generated CSS simply by:

import CSS from "./style.css";
console.log(CSS);

Regarding "You may need an additional loader to handle the result of these loaders" error. Have you used a css-loader? You can't just use stylus-loader alone. Because it is CSS, and CSS should be handled by css-loader first. Try this:

    // webpack.config.js

module.exports = {
...
  module: {
    rules: [
      ...
      {
        test: /.styl$/,
        use: [
          'css-loader',
          'stylus-loader'
          
        ]
      }
      ...
   ]
...
};
Vadim
  • 1,125
  • 8
  • 18
  • Thank you for the answer! "Have you used a css-loader?" - I tried import styles from "!css-loader!stylus-loader!@Assets/Styles/Typography/ArticleFormatting.styl"; The `styles` was an array, not the string of CSS styles as expected. I added the update to my question. – Takeshi Tokugawa YD Jan 12 '22 at 06:11