postcss/postcss-import

Eleventy + postcss-import, a question

pepelsbey opened this issue · 2 comments

Hello! It’s rather a question than an issue or a bug. I’d appreciate any help or guidance. Let me know if it’s not the right place for that.

So, I’m trying to use this plugin with Eleventy’s new custom templates. Basically, I’d like to process CSS files during the build process using PostCSS. And it works! But only with postcss-csso plugin: once I add postcss-import, everything stops working.

CSSO

Here’s example with just the postcss-csso plugin:

config.addExtension('css', {
  outputFileExtension: 'css',
  compile: async (inputContent, inputPath) => {
    if (inputPath.endsWith('index.css')) {
      let result;
      postcss([csso])
        .process(inputContent, { from: inputPath })
        .then((output) => {
          result = output.css;
          console.log(result); // it’s here!
        });
      return async () => {
        return result; // and here!
      }
    }
  }
});

As a result, index.css file goes to dist folder minified, as expected.

PostCSS Import

But once I use postcss-import (sorry I call it pimport), Eleventy silently fails to write a file:

config.addExtension('css', {
  outputFileExtension: 'css',
  compile: async (inputContent, inputPath) => {
    if (inputPath.endsWith('index.css')) {
      let result;
      postcss([pimport])
        .process(inputContent, { from: inputPath })
        .then((output) => {
          result = output.css;
          console.log(result); // it’s here!
        });
      return async () => {
        return result; // but not here :(
      }
    }
  }
});

Actually, console.log(result) delivers what I need, but it somehow misses the last function.

I guess it’s related to async, but I’m not sure how to pass the result to the right place at the right moment.

Yeah, postcss-import is an async plugin, and you're not handling the async data correctly. Try this:

config.addExtension('css', {
  outputFileExtension: 'css',
  compile: async (inputContent, inputPath) => {
    if (inputPath.endsWith('index.css')) {
      const output = await postcss([pimport])
        .process(inputContent, { from: inputPath });
      return async () => {
        return output.css;
      }
    }
  }
});

@RyanZim it works, thank you!