jonschlinkert/gray-matter

Typescript Import

fireflysemantics opened this issue · 3 comments

I don't think this line in the README makes sense ...

import matter = require('gray-matter');

At least VS Code red lines it with the error:

Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead.ts(1202)

This works:

import * as matter from 'gray-matter';

Actually nix that. VSCode does not complain but it does not work. This works:

import matter from 'gray-matter'

Here's a stackblitz

https://stackblitz.com/edit/gray-matter

Outside of Stackblitz we also need to set this compiler options in tsconfig.lib:

  "compilerOptions": {
    "allowSyntheticDefaultImports": true,

Last thing - for Angular 9 this needs to be added to polyfills.js:

(window as any).global = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
(window as any).process = {
  version: ''
};

Related SO:
https://stackoverflow.com/questions/60772266/getting-buffer-is-not-defined-when-using-gray-matter-in-angular/60772329#60772329

import * as matter from 'gray-matter';

only works if you then call it like

matter.default('---\ntitle: Front Matter\n---\nThis is content.');

Or import like you suggested import matter from 'gray-matter'

When

matter.default('---\ntitle: Front Matter\n---\nThis is content.');

it says

Property 'default' does not exist on type 'typeof matter'.ts(2339)
dontic commented

For being abandoned the package works well enough. I just had this issue when importing it as there are no types declarations for it.

I created gray-matter.d.ts in the root of my React project with the following content.

Please take into account that I created it based on the documentation and my use case (React + TS), this might not suffice in all cases.

declare module "gray-matter" {
  namespace grayMatter {
    interface GrayMatterFile<T = any> {
      content: string;
      data: {
        [key: string]: any;
      };
      excerpt: string;
      isEmpty: boolean;
      orig: Uint8Array;
    }
  }

  function grayMatter<T = any>(
    str: string,
    options?: {
      excerpt?: boolean | function;
      excerpt_separator?: string;
      engines?: any;
      language?: string;
      delimiters?: string | string[];
    }
  ): grayMatter.GrayMatterFile<T>;

  export = grayMatter;
}

Then I just import matter from "gray-matter"; and all the declared options and types should be available.