本文整理汇总了TypeScript中postcss.plugin函数的典型用法代码示例。如果您正苦于以下问题:TypeScript plugin函数的具体用法?TypeScript plugin怎么用?TypeScript plugin使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了plugin函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: postcssNodeExtract
export = function postcssNodeExtract(
filterNames: string|string[],
customFilters?: ICustomFilter,
preserveLines = false,
) {
const filterNamesArray = Array.isArray(filterNames) ? filterNames : [filterNames];
Object.assign(filterDefinitions, customFilters);
return postcss.plugin(`postcss-node-extract`, () => (nodes) => {
nodes.walk((rule) => {
let filterRule = false;
filterNamesArray.some((filterName) => {
const filterNameCamelCase = camelCase(filterName);
filterRule = extractNodeRecursively(rule, filterDefinitions[filterNameCamelCase]);
return filterRule;
});
if (!filterRule) {
if (preserveLines) {
const ruleLines = rule.toString().split(/\r\n|\r|\n/).length;
rule.cloneBefore({
type: `comment`,
text: `${PRESERVE_LINES_START}${'\n'.repeat(ruleLines - 1)}${PRESERVE_LINES_END}`,
raws: Object.assign(rule.raws, { left: ' ', right: ' ' }),
});
}
rule.remove();
}
});
});
};
示例2: postcssSelectorExtract
export = function postcssSelectorExtract(filters: ISelectorFilter[]|string[] = [], preserveLines = false) {
return postcss.plugin(`postcss-extract-selectors`, () => (nodes) => {
// We have to force `any` type, because postcss type
// definitions seem to be outdated.
nodes.walkRules((rule: any) => {
const ruleSelectors = rule.selector
.split(`,`)
.map((ruleSelector: any) => ruleSelector.replace(/(\r\n|\n|\r)/gm, ``).trim())
.map((ruleSelector: any) => filterSelector({
ruleSelector,
ruleParentSelectors: rule.parent.selector ? rule.parent.selector.split(`,`) : [],
filters,
}))
.filter((ruleSelector: any) => ruleSelector.length);
if (ruleSelectors.length) {
rule.selector = ruleSelectors.join(`,`);
} else {
if (preserveLines) {
const ruleLines = rule.toString().split(/\r\n|\r|\n/).length;
rule.cloneBefore({
type: `comment`,
text: `${PRESERVE_LINES_START}${'\n'.repeat(ruleLines - 1)}${PRESERVE_LINES_END}`,
raws: Object.assign(rule.raws, { left: ' ', right: ' ' }),
});
}
rule.remove();
}
});
// Remove empty @ rules.
nodes.walkAtRules((rule) => {
if (rule.nodes && !rule.nodes.length) {
rule.remove();
}
});
});
};
示例3: async
export default postcss.plugin('postcss-cli-resources', (options: PostcssCliResourcesOptions) => {
const { deployUrl, filename, loader } = options;
const process = async (inputUrl: string, resourceCache: Map<string, string>) => {
// If root-relative or absolute, leave as is
if (inputUrl.match(/^(?:\w+:\/\/|data:|chrome:|#|\/)/)) {
return inputUrl;
}
// If starts with a caret, remove and return remainder
// this supports bypassing asset processing
if (inputUrl.startsWith('^')) {
return inputUrl.substr(1);
}
const cachedUrl = resourceCache.get(inputUrl);
if (cachedUrl) {
return cachedUrl;
}
const { pathname, hash, search } = url.parse(inputUrl.replace(/\\/g, '/'));
const resolver = (file: string, base: string) => new Promise<string>((resolve, reject) => {
loader.resolve(base, file, (err, result) => {
if (err) {
reject(err);
return;
}
resolve(result);
});
});
const result = await resolve(pathname as string, loader.context, resolver);
return new Promise<string>((resolve, reject) => {
loader.fs.readFile(result, (err: Error, content: Buffer) => {
if (err) {
reject(err);
return;
}
const outputPath = interpolateName(
{ resourcePath: result } as webpack.loader.LoaderContext,
filename,
{ content },
);
loader.addDependency(result);
loader.emitFile(outputPath, content, undefined);
let outputUrl = outputPath.replace(/\\/g, '/');
if (hash || search) {
outputUrl = url.format({ pathname: outputUrl, hash, search });
}
if (deployUrl) {
outputUrl = url.resolve(deployUrl, outputUrl);
}
resourceCache.set(inputUrl, outputUrl);
resolve(outputUrl);
});
});
};
return (root) => {
const urlDeclarations: Array<postcss.Declaration> = [];
root.walkDecls(decl => {
if (decl.value && decl.value.includes('url')) {
urlDeclarations.push(decl);
}
});
if (urlDeclarations.length === 0) {
return;
}
const resourceCache = new Map<string, string>();
return Promise.all(urlDeclarations.map(async decl => {
const value = decl.value;
const urlRegex = /url\(\s*(?:"([^"]+)"|'([^']+)'|(.+?))\s*\)/g;
const segments: string[] = [];
let match;
let lastIndex = 0;
let modified = false;
// tslint:disable-next-line:no-conditional-assignment
while (match = urlRegex.exec(value)) {
const originalUrl = match[1] || match[2] || match[3];
let processedUrl;
try {
processedUrl = await process(originalUrl, resourceCache);
} catch (err) {
loader.emitError(decl.error(err.message, { word: originalUrl }).toString());
continue;
}
if (lastIndex < match.index) {
segments.push(value.slice(lastIndex, match.index));
}
//.........这里部分代码省略.........
示例4: myplugin
module.exports = postcss.plugin('postcss-colour-functions', function myplugin(options) {
return function(css) {
options = options || {};
let requestedFunction = {},
colour,
amount,
newVal;
css.walkRules(function(rule) {
rule.walkDecls(function(decl, i) {
let val = decl.value;
for (let i in functions) {
if (val.indexOf(i) !== -1) {
let regex = new RegExp(i+"\\([a-zA-Z0-9\\)\\.\\#\\,\\s\\%]+");
requestedFunction = {
'function': i,
'request': val.match(regex)['input']
.replace(/\(/g, '')
.replace(/\)/g, '')
.replace(i, '')
.split(',')
};
if (requestedFunction['request'] !== undefined){
let possibleColour = requestedFunction['request'][0];
if (possibleColour.indexOf('#') != -1) {
colour = hexToRgb(possibleColour);
amount = requestedFunction['request'][1];
} else if (possibleColour.indexOf('rgb') != -1) {
colour = stripRgb(requestedFunction['request']);
amount = requestedFunction['request'][requestedFunction['request'].length - 1];
} else if (possibleColour.match(/[a-z]+/i) !== undefined){
if (colourCodes.hasOwnProperty(possibleColour)){
colour = hexToRgb(colourCodes[possibleColour]);
amount = requestedFunction['request'][1];
}else{
var errorMessage = 'POSTCSS-COLOUR-FUNCTIONS: No colour code found for ' + possibleColour +'. Are you trying to use a CSS colour code?';
throw new Error(errorMessage);
}
} else {
throw new Error('POSTCSS-COLOUR-FUNCTIONS: Colour entry must be in RGB or a hex code value');
}
if (functions[i] == opacityColour || colour.hasOwnProperty('a')){
newVal = 'rgba(' + functions[i](colour, amount).join(',') + ')';
}else{
newVal = 'rgb(' + functions[i](colour, amount).join(',') + ')';
}
decl.value = newVal;
requestedFunction = {};
}
break;
}
}
});
});
}
});
示例5: async
export default postcss.plugin('postcss-cli-resources', (options: PostcssCliResourcesOptions) => {
const {
deployUrl = '',
baseHref = '',
filename,
loader,
} = options;
const dedupeSlashes = (url: string) => url.replace(/\/\/+/g, '/');
const process = async (inputUrl: string, context: string, resourceCache: Map<string, string>) => {
// If root-relative, absolute or protocol relative url, leave as is
if (/^((?:\w+:)?\/\/|data:|chrome:|#)/.test(inputUrl)) {
return inputUrl;
}
// If starts with a caret, remove and return remainder
// this supports bypassing asset processing
if (inputUrl.startsWith('^')) {
return inputUrl.substr(1);
}
const cacheKey = path.resolve(context, inputUrl);
const cachedUrl = resourceCache.get(cacheKey);
if (cachedUrl) {
return cachedUrl;
}
if (inputUrl.startsWith('~')) {
inputUrl = inputUrl.substr(1);
}
if (inputUrl.startsWith('/')) {
let outputUrl = '';
if (deployUrl.match(/:\/\//) || deployUrl.startsWith('/')) {
// If deployUrl is absolute or root relative, ignore baseHref & use deployUrl as is.
outputUrl = `${deployUrl.replace(/\/$/, '')}${inputUrl}`;
} else if (baseHref.match(/:\/\//)) {
// If baseHref contains a scheme, include it as is.
outputUrl = baseHref.replace(/\/$/, '') + dedupeSlashes(`/${deployUrl}/${inputUrl}`);
} else {
// Join together base-href, deploy-url and the original URL.
outputUrl = dedupeSlashes(`/${baseHref}/${deployUrl}/${inputUrl}`);
}
resourceCache.set(cacheKey, outputUrl);
return outputUrl;
}
const { pathname, hash, search } = url.parse(inputUrl.replace(/\\/g, '/'));
const resolver = (file: string, base: string) => new Promise<string>((resolve, reject) => {
loader.resolve(base, file, (err, result) => {
if (err) {
reject(err);
return;
}
resolve(result);
});
});
const result = await resolve(pathname as string, context, resolver);
return new Promise<string>((resolve, reject) => {
loader.fs.readFile(result, (err: Error, content: Buffer) => {
if (err) {
reject(err);
return;
}
const outputPath = interpolateName(
{ resourcePath: result } as webpack.loader.LoaderContext,
filename,
{ content },
);
loader.addDependency(result);
loader.emitFile(outputPath, content, undefined);
let outputUrl = outputPath.replace(/\\/g, '/');
if (hash || search) {
outputUrl = url.format({ pathname: outputUrl, hash, search });
}
if (deployUrl && loader.loaders[loader.loaderIndex].options.ident !== 'extracted') {
outputUrl = url.resolve(deployUrl, outputUrl);
}
resourceCache.set(cacheKey, outputUrl);
resolve(outputUrl);
});
});
};
return (root) => {
const urlDeclarations: Array<postcss.Declaration> = [];
root.walkDecls(decl => {
if (decl.value && decl.value.includes('url')) {
//.........这里部分代码省略.........
示例6: require
import * as postcss from 'postcss'
import CleanCSS = require('clean-css')
export default postcss.plugin('clean', options => {
const clean = new CleanCSS({ compatibility: 'ie9', ...options })
return (css: any, res: any) => {
const output = clean.minify(css.toString())
res.root = postcss.parse(output.styles)
}
})
示例7: plugin
export default plugin("postcss-shared-options", function(opts: Option) {
return function(css: Container, result: Result) {
const dir = path.dirname(
css.source.input.file || opts.from || ""
);
const hash = md5(css.source.input.css);
const confs: Array<ParserNodes> = [];
css.walkAtRules("shared", (shared) => {
const expr = parseExpression(shared.params);
if (expr.error) {
shared.warn(result, expr.error, { plugin: "postcss-shared-options" });
} else {
confs.push(expr);
shared.remove();
}
});
const read: (absPath: string) => Promise.IThenable<Config> = _.memoize(readVariables);
return Promise.all(confs.map(
(conf) => read(path.resolve(dir, conf.path))
.then((vars) => {
const buf: { [key: string]: string } = {};
const varsKeys = Object.keys(vars.values);
// test that export variable exists
const errors = conf.values.reduce((memo, key) => {
if (varsKeys.indexOf(key) === -1) {
memo[memo.length] = key;
}
return memo;
}, []);
const values = _.reduce(vars.values, (memo, val, key) => {
if (conf.values.indexOf(key) > -1) {
memo[key] = val;
}
return memo;
}, buf);
return { path: vars.path, values, errors };
})
))
.then(
(args) => {
return _.reduce(args, (memo, item) => {
const ptr = _.find(memo, (it) => it.path === item.path);
if (ptr) {
ptr.values = _.merge(ptr.values, item.values);
} else {
memo = memo.concat(item);
}
return memo;
}, []);
})
.then(
(imports) => {
const mapVars: { [key: string]: string } = {};
imports.forEach((c) => {
const relPath = path.relative(dir, c.path);
const hashImport = md5(relPath + hash);
let rootRule: postcss.Rule = null;
const getRootRule = (): postcss.Rule => {
css.walkRules(":root", (root) => {
!rootRule && (rootRule = root);
});
if (!rootRule) {
rootRule = postcss.rule({
selector: ":root"
});
css.prepend(rootRule);
}
return rootRule;
};
_.each(c.values, (value, p) => {
const prop = p + "-" + hashImport;
mapVars[p] = prop;
const decl = postcss.decl({
value, prop,
raws: { before: "\n " }
});
getRootRule().append(decl);
});
});
const allErrors = imports.reduce((memo, item) => {
return memo.concat(item.errors);
}, []);
if (allErrors.length && css.nodes[0]) {
const messages = allErrors.join(" ");
css.nodes[0].warn(
result,
`Variables doesn't exists: ${messages}`,
{ plugin: "postcss-shared-options" }
);
}
css.walkAtRules((atRule) => {
atRule.params = processVars(atRule.params, mapVars);
});
css.walkDecls((decl) => {
decl.value = processVars(decl.value, mapVars);
});
//.........这里部分代码省略.........
示例8: rewriteSelector
export default postcss.plugin('add-id', (options: any) => (root: Root) => {
const id: string = options
const keyframes = Object.create(null)
root.each(function rewriteSelector (node: any) {
if (!node.selector) {
// handle media queries
if (node.type === 'atrule') {
if (node.name === 'media' || node.name === 'supports') {
node.each(rewriteSelector)
} else if (/-?keyframes$/.test(node.name)) {
// register keyframes
keyframes[node.params] = node.params = node.params + '-' + id
}
}
return
}
node.selector = selectorParser((selectors: any) => {
selectors.each((selector: any) => {
let node = null
selector.each((n: any) => {
// ">>>" combinator
if (n.type === 'combinator' && n.value === '>>>') {
n.value = ' '
n.spaces.before = n.spaces.after = ''
return false
}
// /deep/ alias for >>>, since >>> doesn't work in SASS
if (n.type === 'tag' && n.value === '/deep/') {
const prev = n.prev()
if (prev && prev.type === 'combinator' && prev.value === ' ') {
prev.remove()
}
n.remove()
return false
}
if (n.type !== 'pseudo' && n.type !== 'combinator') {
node = n
}
})
selector.insertAfter(node, selectorParser.attribute({
attribute: id
}))
})
}).processSync(node.selector)
})
// If keyframes are found in this <style>, find and rewrite animation names
// in declarations.
// Caveat: this only works for keyframes and animation rules in the same
// <style> element.
if (Object.keys(keyframes).length) {
root.walkDecls(decl => {
// individual animation-name declaration
if (/^(-\w+-)?animation-name$/.test(decl.prop)) {
decl.value = decl.value.split(',')
.map(v => keyframes[v.trim()] || v.trim())
.join(',')
}
// shorthand
if (/^(-\w+-)?animation$/.test(decl.prop)) {
decl.value = decl.value.split(',')
.map(v => {
const vals = v.trim().split(/\s+/)
const i = vals.findIndex(val => keyframes[val])
if (i !== -1) {
vals.splice(i, 1, keyframes[vals[i]])
return vals.join(' ')
} else {
return v
}
})
.join(',')
}
})
}
})
示例9:
import { Root } from 'postcss'
import * as postcss from 'postcss'
export default postcss.plugin('trim', () => (css: Root) => {
css.walk(({ type, raws }) => {
if (type === 'rule' || type === 'atrule') {
raws.before = raws.after = '\n'
}
})
})
示例10:
import postcss from 'postcss';
const plugin = 'postcss-foo';
export default postcss.plugin<Foo.Options>(plugin, options => {
// Type "options." below and you should see
// bar (property) Foo.Options.bar: string
// options.
return root => {};
});
export module Foo {
export interface Options {
bar?: string;
}
}