node.js - 由于 undefined variable 的 postcss 规则,编译 scss 文件的 NodeJs 脚本失败

标签 node.js sass postcss

我正在使用 scss-bundle导入 scss归档并解决他的所有问题 @import语句稍后再次将其保存为 scss文件。

这工作正常,下面是一个例子,看看它是如何工作的:

scss-bundle.ts

import { Bundler } from 'scss-bundle';
import { relative } from 'path';
import { writeFile } from 'fs-extra';

/** Bundles all SCSS files into a single file */
async function bundleScss(input, output) {
  const {found, bundledContent, imports} = await new Bundler()
    .Bundle(input, ['./src/styles/**/*.scss']);
  if (imports) {
    const cwd = process.cwd();

    const filesNotFound = imports
      .filter((x) => !x.found)
      .map((x) => relative(cwd, x.filePath));

    if (filesNotFound.length) {
      console.error(`SCSS imports failed \n\n${filesNotFound.join('\n - ')}\n`);
      throw new Error('One or more SCSS imports failed');
    }
  }

  if (found) {
    await writeFile(output, bundledContent);
  }
}

bundleScss('./src/styles/file-to-import.scss', './src/styles/imported-file.scss');

哪里file-to-import.scss是以下文件:
@import './file-to-import-1';
@import './file-to-import-2';

file-to-import-1.scssfile-to-import-2.scss是以下文件:

file-to-import-1.scss
.price-range {
  background-color: $range-header-background-1;
}

file-to-import-2.scss
.qr-code {
  background-color: $range-header-background-2;
}

执行脚本的结果是:

导入文件.scss :
.price-range {
  background-color: $range-header-background-1;
}

.qr-code {
  background-color: $range-header-background-2;
}


直到这一切都运行良好。

现在... 我想用postcss-css-modules为了散列类的名称,结果应该是这样的:

导入文件.scss 散列后
._3BQkZ {
  background-color: $range-header-background-1;
}

.Xb2EV {
  background-color: $range-header-background-2;
}

我已经实现了这一点,但前提是我定义了变量 $range-header-background-1$range-header-background-2 .

但是,我还不能定义变量,因为我需要在运行时将它们定义为 Http 请求的查询参数。

如果我在没有定义变量的情况下运行脚本,则会显示以下错误:
(node:1972) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): CssSyntaxError: <css input>:372:14: Unknown word
(node:1972) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是scss-budle.tspostcss-css-modules称呼:
import { Bundler } from 'scss-bundle';
import { relative } from 'path';
import * as path from 'path';
import { writeFile } from 'fs-extra';
import * as postcssModules from 'postcss-modules';
import * as postcss from 'postcss';
import * as fs from 'fs';

/** Bundles all SCSS files into a single file */
async function bundleScss(input, output) {
  const {found, bundledContent, imports} = await new Bundler()
    .Bundle(input, ['./src/styles/**/*.scss']);
  if (imports) {
    const cwd = process.cwd();

    const filesNotFound = imports
      .filter((x) => !x.found)
      .map((x) => relative(cwd, x.filePath));

    if (filesNotFound.length) {
      console.error(`SCSS imports failed \n\n${filesNotFound.join('\n - ')}\n`);
      throw new Error('One or more SCSS imports failed');
    }
  }

  if (found) {
    await writeFile(output, bundledContent);

    const hashedResult = await postcss().use(postcssModules({
      generateScopedName: '[hash:base64:5]',
      getJSON(cssFileName: any, json: any, outputFileName: any) {
        let jsonFileName = path.resolve('./src/styles/imported-file.json');
        fs.writeFileSync(jsonFileName, JSON.stringify(json));
      }
    })).process(bundledContent);
    await writeFile(output.replace('.scss', '-hashed.scss'), hashedResult.css, 'utf8');
    return;
  }

}

bundleScss('./src/styles/file-to-import.scss', './src/styles/imported-file.scss');

有谁知道如何继续执行postcss-css-modules没有因为未定义 scss 变量而停止?

提前致谢。

最佳答案

我能够使用 postcss-scss 成功运行脚本作为 postcss 的解析器:

import * as postcssScss from 'postcss-scss';

...

const hashedResult = await postcss([
  postcssModules({
    generateScopedName: '[hash:base64:8]',
    getJSON(cssFileName: any, json: any, outputFileName: any) {
        let jsonFileName = path.resolve('./src/styles/imported-file.json');
        fs.writeFileSync(jsonFileName, JSON.stringify(json));
    }
  })
]).process(bundledContent, { parser: postcssScss});



下面,我让脚本完整:

scss-bundle.ts
import { Bundler } from 'scss-bundle';
import { relative } from 'path';
import * as path from 'path';
import { writeFile } from 'fs-extra';
import * as postcssModules from 'postcss-modules';
import * as postcss from 'postcss';
import * as fs from 'fs';
import * as postcssScss from 'postcss-scss';

/** Bundles all SCSS files into a single file */
async function bundleScss(input, output) {
  const {found, bundledContent, imports} = await new Bundler()
    .Bundle(input, ['./src/styles/**/*.scss']);
  if (imports) {
    const cwd = process.cwd();

    const filesNotFound = imports
      .filter((x) => !x.found)
      .map((x) => relative(cwd, x.filePath));

    if (filesNotFound.length) {
      console.error(`SCSS imports failed \n\n${filesNotFound.join('\n - ')}\n`);
      throw new Error('One or more SCSS imports failed');
    }
  }

  if (found) {
    await writeFile(output, bundledContent);

    const hashedResult = await postcss([
      postcssModules({
        generateScopedName: '[hash:base64:8]',
        getJSON(cssFileName: any, json: any, outputFileName: any) {
            let jsonFileName = path.resolve('./src/styles/imported-file.json');
            fs.writeFileSync(jsonFileName, JSON.stringify(json));
        }
      })
    ]).process(bundledContent, { parser: postcssScss});
    await writeFile(output.replace('.scss', '-hashed.scss'), hashedResult.css, 'utf8');
    return;
  }
}

bundleScss('./src/styles/file-to-import.scss', './src/styles/imported-file.scss');

关于node.js - 由于 undefined variable 的 postcss 规则,编译 scss 文件的 NodeJs 脚本失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60712566/

相关文章:

html - 如何让导航元素在CSS中的每个导航元素之后都有水平线

css - 样式组件也可以在服务器上呈现吗?

css - nuxt 样式不会应用于生产模式

npm - Gulp v4 监视任务

node.js - 无法完成 "npm run deploy"命令以便 React 在 Github Pages 上使用

javascript - 使用 Express 和 HTTPS.get 或 HTTPS.request 的最佳方式

css - 将 sass 文件捆绑到单个 sass 文件中

javascript - 使用变量访问嵌套数组中的嵌套对象(MongoDB、Node、Inc)

node.js - 用于简单缓存的 Node 缓存与 Redis

css - Yeoman 生成的 webapp 元素中 dist 文件夹中的空 css 文件