UNPKG

1.48 kBJavaScriptView Raw
1const loadPlugins = require('../utils/loadPlugins');
2const posthtml = require('posthtml');
3const posthtmlParse = require('posthtml-parser');
4
5async function parse(code, asset) {
6 var config = await getConfig(asset);
7 if (!config) {
8 config = {};
9 }
10 return posthtmlParse(code, config);
11}
12
13async function transform(asset) {
14 let config = await getConfig(asset);
15 if (!config) {
16 return;
17 }
18
19 await asset.parseIfNeeded();
20 let res = await posthtml(config.plugins).process(asset.ast, config);
21
22 asset.ast = res.tree;
23 asset.isAstDirty = true;
24}
25
26async function getConfig(asset) {
27 let config = await asset.getConfig(
28 ['.posthtmlrc', '.posthtmlrc.js', 'posthtml.config.js'],
29 {
30 packageKey: 'posthtml'
31 }
32 );
33 if (!config && !asset.options.minify) {
34 return;
35 }
36
37 config = config || {};
38 const plugins = config.plugins;
39 if (typeof plugins === 'object') {
40 // This is deprecated in favor of result messages but kept for compatibility
41 // See https://github.com/posthtml/posthtml-include/blob/e4f2a57c2e52ff721eed747b65eddf7d7a1451e3/index.js#L18-L26
42 const depConfig = {
43 addDependencyTo: {
44 addDependency: name =>
45 asset.addDependency(name, {includedInParent: true})
46 }
47 };
48 Object.keys(plugins).forEach(p => Object.assign(plugins[p], depConfig));
49 }
50 config.plugins = await loadPlugins(plugins, asset.name);
51 config.skipParse = true;
52 return config;
53}
54
55module.exports = {parse, transform};