Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include/Extend from multiple directories #2499

Closed
B7th opened this issue Aug 23, 2016 · 2 comments
Closed

Include/Extend from multiple directories #2499

B7th opened this issue Aug 23, 2016 · 2 comments

Comments

@B7th
Copy link

B7th commented Aug 23, 2016

I have the impression it is currently impossible to have more than one path for includes and extends, unless directly stated in the pug files.

I would like this option available in a similar fashion to stylus' option "paths", which checks file existence in path order. Could it be possible?

@JonDotsoy
Copy link

JonDotsoy commented Aug 24, 2016

an example? I did not understand well.

What!?

@TimothyGu
Copy link
Member

It is not possible out-of-the-box, but you can write a simple plugin for this:

const {accessSync, constants: {R_OK}} = require('fs');
const {dirname, resolve} = require('path');
const pug = require('pug');

const exists = filename => {
  try {
    accessSync(filename, R_OK);
    return true;
  } catch (err) {
    return false;
  }
};

function MultiplePathsPlugin({paths = []}) {
  return {
    name: 'multiplePaths',
    resolve(filename, source) {
      let out;

      if (filename[0] === '/') {
        filename = filename.substr(1);
        if (!paths.some(path => exists(out = resolve(path, filename)))) {
          throw new Error(`${filename} cannot be found in any paths`);
        }
      } else {
        if (!source) {
          throw new Error('the "filename" option is required to use includes and extends with "relative" paths');
        }

        out = resolve(dirname(source), filename);
      }

      return out;
    }
  };
}

console.log(pug.compileFile(sourceFile, {
  plugins: [
    MultiplePathsPlugin({
      paths: ['sales', 'common']
    })
  ]
})());
//- this one uses the classic resolving algorithm
include sameDir.pug
//- these ones are resolved against `paths`
include /inc.pug
include /alt.pug

//-
  you can tweak the `resolve` method in the JS code above,
  so that for example all paths, not just the "absolute" ones,
  are looked for in `paths`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants