【问题标题】:Use autoprefixer synchronously同步使用自动前缀
【发布时间】:2016-06-26 21:32:33
【问题描述】:

我想在我的节点应用程序中使用 autoprefixer 来编译 css。 对于我的特定需求,我想在没有回调或承诺的情况下调用 autoprefixer。

简单:

var result = autoprefixer.process(css);

var result = myPrefixerWrap(css);

我正在为此奋斗一段时间,请你帮帮我。

谢谢你

ps:我已经尝试过 postcss-js,但结果是一个 json 对象供反应使用,而不是纯 css。例如 {borderRadius:"5px"}

var prefixer    = postcssJs.sync([ autoprefixer ]);
var cssCompiled = postcss.parse(css);
var cssObject   = postcssJS.objectify(cssCompiled);
var autoResult  = prefixer(cssObject);

【问题讨论】:

  • 是什么阻止你使用 Promise? (并不是说这不是一件有意义的事情,只是好奇)
  • 编译 css 只是我的应用程序执行的许多事情/模块中的一步,而且我的大部分代码都没有使用 Promise,我想让事情变得简单。

标签: css node.js autoprefixer postcss


【解决方案1】:

PostCSS 有一个 API 用于同步获取 Processor#processprocess().css,别名为 toString())的结果,只要使用的所有 PostCSS 插件都是同步的(如 Autoprefixer),它就可以工作。这样做的代码很简单:

var postcss = require('postcss'); // import postcss from 'posts';
var autoprefixer = require('autoprefixer'); // import autoprefixer from 'autoprefixer';
postcss([autoprefixer]).process(styleString).css;

注意:我在 Webpack 中使用 postcss-js 时遇到了问题,所以对于那些看到如下错误的人:

Module parse failed: /path/to/node_modules/autoprefixer/node_modules/caniuse-db/features-json/css-regions.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.

或者:

ERROR in ./~/autoprefixer/~/browserslist/index.js
Module not found: Error: Cannot resolve module 'fs' in /path/to/node_modules/autoprefixer/node_modules/browserslist
 @ ./~/autoprefixer/~/browserslist/index.js 3:14-27

查看 postcss-js GitHub 自述文件的 Troubleshooting section,了解您需要添加到 Webpack 配置中以使其正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多