NodeJs Сценарий, который компилирует файлы s css, не работает из-за правила post css для неопределенных переменных - PullRequest
6 голосов
/ 16 марта 2020

Я использую s css -bundle , чтобы импортировать файл scss и разрешить все его операторы @import, чтобы позже сохранить его снова как scss файл.

Это работает нормально, и ниже приведен пример, чтобы увидеть, как это работает:

s css -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 является следующим file:

@import './file-to-import-1';
@import './file-to-import-2';

И file-to-import-1.scss и file-to-import-2.scss - это следующие файлы:

file-to-import-1.s css

.price-range {
  background-color: $range-header-background-1;
}

file-to-import-2.s css

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

Результат выполнения сценария:

import-file.s css:

.price-range {
  background-color: $range-header-background-1;
}

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

До этого все работало хорошо.

Сейчас ... Я хочу использовать post css - css -modules , чтобы иметь sh имена классов, результат должен выглядеть примерно так:

import-file.s css после хеширования

._3BQkZ {
  background-color: $range-header-background-1;
}

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

Я уже достиг этого, но только если определю переменные $range-header-background-1 и $range-header-background-2.

* 105 6 * Однако я пока не могу определить переменные, потому что мне нужно определить их во время выполнения как параметры запроса 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.ts с postcss-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 без остановки, потому что css переменные не определены?

Заранее спасибо.

1 Ответ

0 голосов
/ 23 марта 2020

Мне удалось успешно запустить скрипт, используя post css -s css в качестве парсера post css:

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});


Ниже я оставляю сценарий завершенным:

s css -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');
...