如何在.mjs脚本中使用Node Sass解决别名?

时间:2020-07-21 00:23:33

标签: javascript node.js sass node-sass

我的项目的结构具有用于全局设置等的SCSS库,主要组件scss模块位于其他位置,并带有其相应的组件文件。我设置了Webpack,以便在构建路径别名@时解析它,因此我在运行项目时对@import "@/src/scss/variables/blah-blah.scss"这样的行的使用效果很好。

相反,我有一些实用程序脚本正在做SCSS基准测试,只是一些编译和分析操作以帮助说明我们在进行样式更改时的性能提升。我使用.mjs文件扩展名构建了这些文件,在这里我认为它并不重要,它只是有助于与Typescript很好地玩。

因此,当Node Sass遇到类似@import "@/src/scss/variables/blah-blah.scss"的路径时,它将无法解析该路径。毫无疑问,但是我似乎找不到最佳解决方案来帮助解决脚本中的路径,而不是添加NPM包来完成看似简单的工作。我应该如何处理?

错误来自await sass.render()

import { writeFileSync } from "fs";
import sass from "node-sass";
import tildeImporter from "node-sass-tilde-importer";
import { resolve } from "path";

export const compileCSS = async module => {
  const input = `src/components/${module}/scss/module.scss`;
  const output = `stats/css/${module}.css`;
  await sass.render(
    {
      file: resolve(input),
      importer: tildeImporter,
      outputStyle: "expanded",
      outFile: resolve(output),
      sourceMap: true
    },
    async function(error, result) {
      if (error) {
        await console.log(module, "COMPILE ERROR", error.message);
      } else {
        writeFileSync(resolve(output), result);
        return result;
      }
    }
  );
};

1 个答案:

答案 0 :(得分:0)

进一步的研究表明,尽管有一些想法在工作中,但Node Sass目前还没有实现此目的的好方法。

我通过将统计信息收集操作转换为Webpack加载器模块来进行解决,该模块在步骤之间分析并吐出数据以将编译后的样式打包到包中。这样,我就可以解决别名路径并简化开发经验。这是比我提出的更好的解决方案,所以我很高兴。