Skip to content

Instantly share code, notes, and snippets.

@mkrause
Created November 12, 2024 16:56
Show Gist options
  • Select an option

  • Save mkrause/8a9ae84cb0c6c82e50d440a68dffd5b3 to your computer and use it in GitHub Desktop.

Select an option

Save mkrause/8a9ae84cb0c6c82e50d440a68dffd5b3 to your computer and use it in GitHub Desktop.
Plop helper for generating relative import paths
import * as path from 'node:path';
import { type HelperOptions } from 'handlebars';
import { type NodePlopAPI } from 'plop';
export default (plop: NodePlopAPI) => {
// Compute the relative path from the component file to the given target path.
plop.setHelper('relative-path', (pathTargetFromCwd, options: HelperOptions) => {
if (typeof pathTargetFromCwd !== 'string') { throw new Error(`Missing argument to 'relative-path' helper`); }
const pathComponentFromCwd: undefined | string = options.data?.root?.['component-path'];
if (typeof pathComponentFromCwd !== 'string') { throw new Error(`Missing 'component-path' variable`); }
const pathComponentAbs = path.join(process.cwd(), pathComponentFromCwd);
const pathTargetAbs = path.join(process.cwd(), pathTargetFromCwd);
const pathTargetRel = path.relative(pathComponentAbs, pathTargetAbs);
return pathTargetRel;
});
//...
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment