Ejemplo n.º 1
0
module.exports = postcss.plugin('postcss-atomised', ({json = path.resolve(process.cwd(), 'atomic-map.json')} = {}) => (css, result) => postcss([
    // we check these because it won't work if these are used
    stylelint({
        config: {
            rules: {
                "selector-no-combinator": true,
                "selector-no-attribute": true,
                "selector-no-id": true,
                "selector-no-qualifying-type": true,
                "selector-no-type": true,
                "selector-no-universal": true,
                "declaration-no-important": true
            }
        }
    }),
    reporter({clearMessages: true, throwError: true}),
    unchainSelectors(),
    mergeRules(),
    expandShorthand(),
    dedupeDeclarations(),
    atomise(json),
    mqpacker({sort: true})
]).process(result.root));
Ejemplo n.º 2
0
	return new Promise((resolve, reject) => {
		postcss([
			require('postcss-modules')({
				scopeBehaviour: options.global ? 'global' : 'local',
				generateScopedName: function(name, filename, css) {
					return '_sofe_' + serviceName + '__' + name;
				},
				getJSON: function(cssFileName, _json) {
					json = _json;
				}
			})
		]).process(css, { from: inputFile }).then(function(result) {
			cssnano.process(result.css, { safe: true })
				.then((result) => {
					resolve({
						css: removeWrappingQuotes(result.css),
						exports: json,
					});
				})
				.catch(err => reject(err));
		}).catch(err => reject(err));

	});
test("No comments, but parsing a selector with ().", () => {
  expect.assertions(1);

  postcss()
    .process(
      `
      .dropdown-menu:not(.level-0) {
        margin: 0;

        a {
          white-space: normal;
        }
      }
    `,
      { syntax: scss, from: undefined }
    )
    .then(result => {
      const css = result.root.source.input.css;
      const comments = findCommentsInRaws(css);
      expect(comments.length).toBe(0);
    })
    .catch(logError);
});
Ejemplo n.º 4
0
        tree.nodes.forEach(function (node, index) {
            var start = new Date();
            var input = node.data.toString('utf8');

            var prevSourceMap = bygglib.tree.sourceMap.get(node);
            var opts = {
                from: node.name,
                map: {
                    prev: prevSourceMap !== undefined ? prevSourceMap : false,
                    sourcesContent: true,
                    annotation: false
                }
            };

            postcss(plugins)
                .process(input, opts)
                .then(function (result) {
                    var outputNode = bygglib.tree.cloneNode(node);
                    outputNode.data = new Buffer(result.css, 'utf8');

                    var sourceMap = JSON.parse(result.map);
                    outputNode = bygglib.tree.sourceMap.set(outputNode, sourceMap, {
                        sourceBase: path.dirname(node.name)
                    });

                    nodes[index] = outputNode;
                    processed++;

                    if (processed === tree.nodes.length) {
                        bygglib.logger.log(name || 'postcss', 'Processed ' + tree.nodes.length + ' stylesheets');
                        output.push(bygglib.tree(nodes));
                    }
                })
                .catch(function (error) {
                    bygglib.logger.error(name || 'postcss', error.message);
                });
        });
Ejemplo n.º 5
0
    style.on('end', function(err, css){

      // configure the options to be passed to autoprefixer
      var process_opts = {
        from: filename,
        to: path.join(
          path.dirname(filename),
          path.basename(filename, path.extname(filename))
        ) + '.css'
      }

      // if there is a stylus sourcemap, ensure autoprefixer also generates one
      if (style.sourcemap) {
        process_opts.map = { annotation: false }
      }

      // run autoprefixer
      var res = postcss([ap(opts)]).process(css, process_opts);

      // if sourcemaps are generated, combine the two
      if (res.map && style.sourcemap) {
        var combined_map = map.transfer({
          fromSourceMap: res.map.toString(),
          toSourceMap: style.sourcemap
        });

        // then set the combined result as the new sourcemap
        style.sourcemap = JSON.parse(combined_map);
      }

      if (showWarnings) {
        res.warnings().forEach(console.error);
      }

      // return the css output
      return res.css;
    });
Ejemplo n.º 6
0
function createComponent({ options = {} }: { options?: Object } = {}) {
  return createChunkTransformer({
    name: manifest.name,
    version: manifest.version,
    async callback({ filePath, format, contents, sourceMap }) {
      if (format !== 'css') return null

      const processed = await postcss([
        cssnano({
          preset: 'default',
          ...options,
        }),
      ]).process(typeof contents === 'string' ? contents : contents.toString(), {
        from: filePath,
        map:
          filePath && sourceMap && sourceMap.filePath
            ? { inline: false, annotation: false, prev: sourceMap.contents, from: filePath }
            : null,
      })
      let { css, map } = processed
      if (filePath && sourceMap && sourceMap.filePath) {
        const relativeUrl = path.posix.relative(path.dirname(filePath), sourceMap.filePath)
        css += `/*# sourceMappingURL=${relativeUrl} */`
        map = JSON.stringify(map)
      } else map = null

      return {
        contents: css,
        sourceMap: map
          ? {
              contents: map,
            }
          : null,
      }
    },
  })
}
Ejemplo n.º 7
0
exports.testPublicInterfaces = function (test) {
  test.expect(5);

  input = '.foo{color:black}';
  expected = postcss.parse(input);
  test.strictEqual(csswring.wring(input).css, expected.toString());

  opts.map = true;
  test.deepEqual(
    csswring.wring(input, opts).map,
    expected.toResult(opts).map
  );
  opts.map = undefined;

  test.strictEqual(
    postcss().use(csswring.processor).process(input).css,
    expected.toString()
  );

  csswring.preserveHacks = true;
  var testCase = 'preserve-hacks';
  input = loadInput(testCase);
  expected = loadExpected(testCase);
  test.strictEqual(csswring.wring(input).css, expected);
  csswring.preserveHacks = false;

  csswring.removeAllComments = true;
  opts.map = true;
  testCase = 'remove-all-comments';
  input = loadInput(testCase);
  expected = loadExpected(testCase);
  test.strictEqual(csswring.wring(input, opts).css, expected);
  csswring.removeAllComments = false;
  opts.map = undefined;

  test.done();
};
Ejemplo n.º 8
0
      .forEach(function(file) {
        var outFile = path.join(metalsmith.destination(), file)
        var plugins = [
          cssnext(),
          autoprefixer(),
          pixrem(),
          mixins(),
          nested(),
          cssnano()
        ]

        postcss(plugins)
          .process(files[file].contents.toString(), {from: file})
          .then(function (result) {
            delete files[file]
            files[outFile] = {
              contents: new Buffer(result.css)
            }

            if (--count === 0) {
              done()
            }
          })
      })
Ejemplo n.º 9
0
  Promise.all(files.map(function (file) {
    var fullPath = path.resolve(process.cwd(), file)

    var css = fs.readFileSync(fullPath, 'utf-8')

    return postcss([stylefmt(options)])
      .process(css, {
        from: fullPath,
        syntax: scss
      })
      .then(function (result) {
        var formatted = result.css
        if (argv.d) {
          return handleDiff(file, css, formatted)
        } else if (css !== formatted) {
          fs.writeFile(fullPath, formatted, function (err) {
            if (err) {
              throw err
            }
          })
          return file
        }
      })
  })).then(function (messages) {
Ejemplo n.º 10
0
module.exports = function reorientCSS(css, from, to, options) {
  // Normalise args
  if (typeof from === 'object') {
    options = from;
    from = options.from;
    to = options.to;
  }
  if (!options){
    options = {};
    options.from = from;
    options.to = to;
  }

  // Validate input
  if (typeof css !== 'string')  throw new TypeError('reorient-css: expected "css" to be a string.');
  if (typeof from !== 'string') throw new TypeError('reorient-css: expected "from" to be a string.');
  if (typeof to !== 'string')   throw new TypeError('reorient-css: expected "to" to be a string.');

  // Normalise to Unix-style paths
  from = from.replace(/\\/g, '/');
  to = to.replace(/\\/g, '/');

  return postcss(module.exports.processor(from, to)).process(css, options);
};
Ejemplo n.º 11
0
test.serial('local imports from files', t => {
  t.plan(6);

  const button = join(localImports, 'styles/button.css');
  const typography = join(localImports, 'styles/typography.css');

  const processor = postcss([
    modulesEs({
      jsFiles: [
        join(localImports, 'App.js'),
        join(localImports, 'Button.js'),
        join(localImports, 'Paragraph.js'),
      ],
      recurse: false,
      getJsExports(name, jsFile) {
        parseWithDefaultOptions(jsFile);
        t.pass();
      },
    }),
  ]);

  return Promise.all([
    processor
      .process(readFileSync(button, 'utf-8'), { from: button })
      .then(({ css, messages }) => {
        t.is(css.indexOf(UNUSED_EXPORT), -1);
        t.is(messages.length, 0);
      }),
    processor
      .process(readFileSync(typography, 'utf-8'), { from: typography })
      .then(({ css, messages }) => {
        t.is(css.indexOf(UNUSED_EXPORT), -1);
        t.is(messages.length, 0);
      }),
  ]);
});
Ejemplo n.º 12
0
test.serial('unused export', t => {
  t.plan(5);

  const button = join(unusedExport, 'styles/button.css');

  const processor = postcss([
    modulesEs({
      jsFiles: join(unusedExport, 'App.js'),
      getJsExports(name, jsFile) {
        parseWithDefaultOptions(jsFile);
        t.pass();
      },
    }),
  ]);

  return processor
    .process(readFileSync(button, 'utf-8'), { from: button })
    .then(({ css, messages }) => {
      t.is(css.indexOf(UNUSED_EXPORT), -1);
      t.is(messages.length, 1);
      t.is(messages[0].type, 'warning');
      t.is(messages[0].text, 'Defined unused style "primary"');
    });
});
Ejemplo n.º 13
0
 fs.readFile('./styles/input.css', (err, css) => {
   if (err) {
     reject(err);
   } else {
     postcss([atImport(), autoprefixer, cssnano()])
       .process(css)
       .then((result) =>
         fse.ensureDir(path.dirname('./public/styles/delft.css'), (err) => {
           if (err) {
             reject(err);
           } else {
             fs.writeFile('./public/styles/delft.css', result, (err) => {
               if (err) {
                 reject(err);
               } else {
                 resolve();
               }
             });
           }
         })
       )
       .catch((err) => reject(err));
   }
 });
Ejemplo n.º 14
0
const styleProcessor = (stylePath, ext, styleFile, callback) => {
  /**
   * Remove comments, autoprefixer, Minifier
   */
  const processors = [
      stripInlineComments,
      autoprefixer,
      cssnano
  ];

  if (/\.(scss|sass)$/.test(ext[0])) {
    let sassObj = sass.renderSync({ file: stylePath });
    if (sassObj && sassObj['css']){
     let css = sassObj.css.toString('utf8');
     postcss(processors).process(css).then(function (result) {
        result.warnings().forEach(function (warn) {
          gutil.warn(warn.toString());
        });
        styleFile = result.css;
        callback(null, styleFile);
    });
    }
  }
};
Ejemplo n.º 15
0
  loadPostcssConfig(vueOptions.postcss).then(config => {
    var plugins = [trim].concat(config.plugins)
    var options = Object.assign({
      to: this.resourcePath,
      from: this.resourcePath,
      map: false
    }, config.options)

    // add plugin for vue-loader scoped css rewrite
    if (query.scoped) {
      plugins.push(scopeId({ id: query.id }))
    }

    // source map
    if (
      this.sourceMap &&
      !this.minimize &&
      vueOptions.cssSourceMap !== false &&
      process.env.NODE_ENV !== 'production' &&
      !options.map
    ) {
      options.map = {
        inline: false,
        annotation: false,
        prev: map
      }
    }

    return postcss(plugins)
      .process(css, options)
      .then(function (result) {
        var map = result.map && result.map.toJSON()
        cb(null, result.css, map)
        return null // silence bluebird warning
      })
  }).catch(e => {
Ejemplo n.º 16
0
  // Process the code through the rule and return
  // the PostCSS LazyResult promise
  function postcssProcess(code) {
    const postcssProcessOptions = {}

    switch (schema.syntax) {
      case "scss":
        postcssProcessOptions.syntax = scssSyntax
        break
      case "less":
        postcssProcessOptions.syntax = lessSyntax
        break
      case "sugarss":
        postcssProcessOptions.syntax = sugarss
        break
    }

    const processor = postcss()
    processor.use(assignDisabledRanges)

    if (schema.preceedingPlugins) {
      schema.preceedingPlugins.forEach(processor.use)
    }

    return processor.use(rule(rulePrimaryOptions, ruleSecondaryOptions)).process(code, postcssProcessOptions)
  }
Ejemplo n.º 17
0
test('integration test: exist output', function (t) {
    var opts = {
        name: 'Default theme',
        src: 'test/input.css',
        dest: 'test/dest/exist/index.html'
    };
    var cwd = process.cwd();
    var src = path.resolve(cwd, 'test/input.css');
    var css = fs.readFileSync(src, 'utf-8');
    t.plan(1);
    postcss([styleGuide(opts)])
      .process(css)
      .then(function () {
        var dest = path.resolve(cwd, 'test/dest/exist/index.html');
        var actual = fs.existsSync(dest);
        var expected = true;
        t.same(actual, expected);
        t.end();
      })
      .catch(function (err) {
        t.error(err);
        t.end();
      });
});
Ejemplo n.º 18
0
var test = function (input, output, done) {
    postcss([ plugin() ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        done();
    });
};
Ejemplo n.º 19
0
Archivo: index.js Proyecto: bbb324/gulp
  stream._transform = function (file, encoding, cb) {

    if (file.isStream()) {
      return handleError('Streams are not supported!')
    }

    // Source map is disabled by default
    var opts = { map: false }
    var attr

    // Extend default options
    if (options) {
      for (attr in options) {
        if (options.hasOwnProperty(attr)) {
          opts[attr] = options[attr]
        }
      }
    }

    opts.from = file.path
    opts.to = opts.to || file.path

    // Generate separate source map for gulp-sourcemap
    if (file.sourceMap) {
      opts.map = { annotation: false }
    }

    postcss(processors)
      .process(file.contents, opts)
      .then(handleResult, handleError)

    function handleResult (result) {
      var map
      var warnings = result.warnings().join('\n')

      file.contents = new Buffer(result.css)

      // Apply source map to the chain
      if (file.sourceMap) {
        map = result.map.toJSON()
        map.file = file.relative
        map.sources = [].map.call(map.sources, function (source) {
          return path.join(path.dirname(file.relative), source)
        })
        applySourceMap(file, map)
      }

      if (warnings) {
        gutil.log('gulp-postcss:', file.relative + '\n' + warnings)
      }

      setImmediate(function () {
        cb(null, file)
      })
    }

    function handleError (error) {
      var errorOptions = { fileName: file.path }
      if (error.name === 'CssSyntaxError') {
        error = error.message + error.showSourceCode()
        errorOptions.showStack = false
      }
      // Prevent stream’s unhandled exception from
      // being suppressed by Promise
      setImmediate(function () {
        cb(new gutil.PluginError('gulp-postcss', error))
      })
    }

  }
Ejemplo n.º 20
0
module.exports.configure = function (config) {
  config = config || {}
  return postcss([this(config.options, config.plugins)])
}
Ejemplo n.º 21
0
module.exports = function (css, map) {
  this.cacheable()
  var cb = this.async()

  var query = loaderUtils.parseQuery(this.query)
  var options = this.options.vue || {}
  var autoprefixOptions = options.autoprefixer
  var postcssOptions = options.postcss

  // postcss plugins
  var plugins
  if (Array.isArray(postcssOptions)) {
    plugins = postcssOptions
  } else if (typeof postcssOptions === 'function') {
    plugins = postcssOptions.call(this, this)
  } else if (isObject(postcssOptions) && postcssOptions.plugins) {
    plugins = postcssOptions.plugins
  }
  plugins = plugins ? plugins.slice() : [] // make sure to copy it

  // scoped css
  if (query.scoped) {
    plugins.push(addId({ id: query.id }))
  }

  // autoprefixer
  if (autoprefixOptions !== false) {
    autoprefixOptions = assign(
      {},
      // also respect autoprefixer-loader options
      this.options.autoprefixer,
      autoprefixOptions
    )
    var autoprefixer = require('autoprefixer')(autoprefixOptions)
    plugins.push(autoprefixer)
  }

  // postcss options, for source maps
  var file = this.resourcePath
  var opts
  opts = {
    from: file,
    to: file,
    map: false
  }
  if (
    this.sourceMap &&
    !this.minimize &&
    options.cssSourceMap !== false &&
    process.env.NODE_ENV !== 'production' &&
    !(isObject(postcssOptions) && postcssOptions.options && postcssOptions.map)
  ) {
    opts.map = {
      inline: false,
      annotation: false,
      prev: map
    }
  }

  // postcss options from configuration
  if (isObject(postcssOptions) && postcssOptions.options) {
    for (var option in postcssOptions.options) {
      if (!opts.hasOwnProperty(option)) {
        opts[option] = postcssOptions.options[option]
      }
    }
  }

  postcss(plugins)
    .process(css, opts)
    .then(function (result) {
      var map = result.map && result.map.toJSON()
      cb(null, result.css, map)
    })
    .catch(function (e) {
      console.log(e)
      cb(e)
    })
}
Ejemplo n.º 22
0
cssnano.process = (css, options = {}) => {
    options.map = options.map || (options.sourcemap ? true : null);
    return postcss([cssnano(options)]).process(css, options);
};
Ejemplo n.º 23
0
module.exports.process = function (css, options, plugins) {
  return postcss([this(options, plugins)]).process(css).css
}
Ejemplo n.º 24
0
'use strict'

// PostCSS
const fs = require('fs')
const postcss = require('postcss')
const atImport = require('postcss-import')
const stylelint = require('stylelint')
const cssnano = require('cssnano')
const reporter = require('postcss-reporter')

// Config
const entry = 'components/app/styles/index.css'
const build = 'build/index.css'
const plugins = [
  atImport(),
  stylelint(),
  cssnano(),
  reporter({ clearMessages: true })
]

postcss(plugins)
  .process(fs.readFileSync(entry, 'utf8'), { from: entry, to: build })
  .then(function (result) {
    fs.writeFileSync(build, result.css)
    if ( result.map ) fs.writeFileSync(build+'.map', result.map)
  })
  .catch(err => console.error(err.stack))
Ejemplo n.º 25
0
import postcss from 'postcss';
import ava from 'ava';
import nano from '..';
import { usePostCSSPlugin } from '../../../../util/testHelpers';

function pluginMacro(t, instance) {
  const css = 'h1 { color: #ffffff }';
  const min = 'h1{color:#fff}';

  return instance.process(css).then((result) => {
    t.deepEqual(result.css, min);
  });
}

ava('can be used as a postcss plugin', pluginMacro, postcss().use(nano()));
ava('can be used as a postcss plugin (2)', pluginMacro, postcss([nano()]));
ava('can be used as a postcss plugin (3)', pluginMacro, postcss(nano));

ava('should use the postcss plugin api', usePostCSSPlugin, nano());

ava('should work with sourcemaps', (t) => {
  return nano
    .process('h1{z-index:1}', { map: { inline: true } })
    .then(({ css }) => {
      const hasMap = /sourceMappingURL=data:application\/json;base64/.test(css);
      t.truthy(hasMap);
    });
});
Ejemplo n.º 26
0
test('test', function (t) {
    var actual = postcss().use(removeBase()).process(css).css.trim()
    var expected = fs.readFileSync('expected.css', 'utf-8').trim()
    t.same(actual, expected)
    t.end()
})
Ejemplo n.º 27
0
function parse(styles, variables = {}) {
  return postcss([plugin({ variables })]).process(styles, { parser });
}
Ejemplo n.º 28
0
exports.pack = function (css, opts) {
  return postcss().use(this.postcss).process(css, opts);
};
Ejemplo n.º 29
0
import sass from 'node-sass'
import { join } from 'path'
import postcss from 'postcss'
import autoprefixer from 'autoprefixer'

var prefixer = postcss([autoprefixer])

// auto compile the sass files on any request
export default function(STATIC_FOLDER) {
  return function (req, res, next) {
    sass.render({
      file: join(STATIC_FOLDER, req.originalUrl),
      indentedSyntax: false,
      omitSourceMapUrl: true
    }, function(err, result) {
      if (!err)
        prefixer
          .process(result.css.toString())
          .then(function (prefixed) {
            res.setHeader('content-type', 'text/css')
            res.send(prefixed.css)
            next()
          })
       else
        throw new Error(err)
    })
  }
}
Ejemplo n.º 30
0
 styles.each(function(index, style) {
   prefixed = postcss([autoprefixer]).process(style.data, autoprefixerOpts).css;
   style.data = prefixed;
 });