LoginSignup
4
4

More than 5 years have passed since last update.

typescriptから自作のJSコードをimportしたい(PEG.jsで作ったParserとか)

Last updated at Posted at 2016-10-21

Pegjsの生成コードに合わせて作成します

tldr

結論としてparser.d.tsを作ります。(parser.jsをpegjsによって生成しimportしたい場合)

対応

peg.jsが出力したParserのコードはexport周辺を見てみると

parser.js
module.exports = /*
 * Generated by PEG.js 0.10.0.
 *
 * http://pegjs.org/
 */
(function() {
  "use strict";

  function peg$subclass(child, parent) {
  function ctor() { this.constructor = child; }
    ctor.prototype = parent.prototype;
    child.prototype = new ctor();
  }


  function peg$SyntaxError(message, expected, found, location) {
    this.message  = message;
    this.expected = expected;
    this.found    = found;
    this.location = location;
    this.name     = "SyntaxError";

    if (typeof Error.captureStackTrace === "function") {
      Error.captureStackTrace(this, peg$SyntaxError);
   }
  }

  peg$subclass(peg$SyntaxError, Error);

/*......*/

  return {
    SyntaxError: peg$SyntaxError,
    parse:       peg$parse
  };
})();

となっているのでparser.d.tsを以下のように作成しました

parser.d.ts
interface ParserOptions {
    startRule?: string;
    tracer: any;
}

/*
      {
                "message":"expect </1> but </2>",
                "expected":null,
                "found":null,
                "location":{"start":{"offset":0,"line":1,"column":1},
                "end":{"offset":13,"line":1,"column":14}},
                "name":"SyntaxError"
            }
*/

export interface Location {
    start:{
        offset: number,
        line: number,
        column: number
    }
    end: {
        offset: number,
        line: number,
        column: number      
    }
}

export declare class SyntaxError extends Error {
  message: string;
  expected: string | null;
  found: string | null;
  location: Location;
  name : 'SyntaxError';
}

export declare function parse(input: string, options?:ParserOptions): 実装に合わせた型;


parser.jsのそばにparser.d.tsを置いておくとimportするときにd.tsの方を見てくれるみたいです。ちなみにトランスパイル出力先にもparser.jsを置いておかないとエラーとなります。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4