postcss: JS API example not working

Hi there. I have a problem… I cant understand how readme example is supposed to work:

var postcss = require('postcss');
postcss([ require('autoprefixer'), require('cssnano') ])
    .process(css, { from: 'src/app.css', to: 'app.css' })
    .then(function (result) {
        fs.writeFileSync('app.css', result.css);
        if ( result.map ) fs.writeFileSync('app.css.map', result.map);
    });

What is css? In the doc you write It is a String with input CSS… but if I have to read my input file and place it as a string to css argument, what is options.from then?

Also, why I should write app.css file in promise then? What is options.to then?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 20 (14 by maintainers)

Most upvoted comments

@Diokuz


const css = fs.readFileSync('./src/app.css', 'utf-8') // {String}

postcss(plugins)
   .process(css, { from: 'src/app.css', to: 'app.css', map: { inline: false } })
   .then((result) => {
      fs.writeFileSync('./app.css', result.css, 'utf-8') // {String}
     // Doesn't need options.from/to to work
      console.log(result.map) 
     // Needs options.from/to to know the path/location of the origin (css) and
     // destination (result.css) to generate the mappings (changes made by postcss plugins)
     //
     // Generated Souremap
     //
     // {
     //   "version": 3,
     //   "file": "app.css", (options.from)
     //   "sources": ["src/app.css"], (options.to)
     //   "mappings": "AAAA,KAAI" 
     // }
   })

@Diokuz I thought about file system shortcut. But it is unnecessary in most of cases:

  1. gulp-postcss gets file content via Gulp API.
  2. postcss-loader gets file content via webpack API.
  3. PostCSS CLI use better reading mechanism to read multiple files faster.
  4. PostCSS for client JS has even no access to fs.

In result there is no good reason to some postcss().readAndWrite() shortcut. Anyway most of PostCSS runners will get file content by other way.

I made JS API example in docs more clear: 2820c76

Thanks for your questions