我需要从“.styl”(Stylus 预处理器)文件导入编译后的 CSS 代码作为字符串。
从逻辑的 Angular 来看:
- 首先我们需要预处理样式。预计
stylus-loader
将使用stylus
预处理器来完成此操作。 - 接下来我们需要原始 CSS 代码。我认为
raw-loader
还不够,因为stylus-loader
返回的不是字符串。
下面的代码:
import styles from "!raw-loader!stylus-loader?@Assets/Styles/Typography/ArticleFormatting.styl";
将返回类似于 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');
// ...
只是
import styles from "!stylus-loader?@Assets/Styles/Typography/ArticleFormatting.styl";
会导致错误:
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;
带有 Stylus 加载器的 CSS 加载器:
import styles from "!raw-loader!stylus-loader!@Assets/Styles/Typography/ArticleFormatting.styl";
像这样导入数组:
[ 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:
}
最佳答案
总体思路是,您可以通过以下方式简单地访问生成的 CSS:
import CSS from "./style.css";
console.log(CSS);
关于“您可能需要额外的加载器来处理这些加载器的结果”错误。您使用过 css-loader
吗?您不能只使用 stylus-loader
。因为它是CSS,而CSS应该首先由css-loader
处理。试试这个:
// webpack.config.js
module.exports = {
...
module: {
rules: [
...
{
test: /.styl$/,
use: [
'css-loader',
'stylus-loader'
]
}
...
]
...
};
关于javascript - 如何使用 Webpack 将预处理的 CSS 作为字符串导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70587829/