1 | const loadPlugins = require('../utils/loadPlugins');
|
2 | const posthtml = require('posthtml');
|
3 | const posthtmlParse = require('posthtml-parser');
|
4 |
|
5 | async function parse(code, asset) {
|
6 | var config = await getConfig(asset);
|
7 | if (!config) {
|
8 | config = {};
|
9 | }
|
10 | return posthtmlParse(code, config);
|
11 | }
|
12 |
|
13 | async 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 |
|
26 | async 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 |
|
41 |
|
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 |
|
55 | module.exports = {parse, transform};
|