简体   繁体   中英

Can't use a class defined in an npm package

I am trying to use a typescript-parser: https://www.npmjs.com/package/typescript-parser

but I'm having difficulties with using the package properly.

I installed the package successfully using npm install ; when I run npm list --depth=0 it shows up in the list.

Eventually, I tried running the following line of code that is suggested in the link attached above (using node command):

const parser = new TypescriptParser();

but the problem is that I get the following error:

const parser = new TypescriptParser();
           ^

ReferenceError: TypescriptParser is not defined
    at Object.<anonymous> (C:\Users\...\parser_example.js:3:16)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js             (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

Alternatively, I tried running this:

const TypescriptParser = require('typescript-parser');

const parser = new TypescriptParser();

yet I still get a (different) error:

const parser = new TypescriptParser();
           ^

TypeError: TypescriptParser is not a constructor
    at Object.<anonymous> (C:\Users\...\parser_example.js:3:16)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

It seems as if although the package was installed, it doesn't recognize the class TypescriptParser.

Any help would be much appreciated!

Try importing using:

import { TypescriptParser } from 'typescript-parser';

I tried the code below and it works for me:

index.js file

const parser = require('typescript-parser');

const parser = new TypescriptParser();

I run it with node index.js

This code works for me:

index.js file

const tp = require('typescript-parser');
const parser = new tp.TypescriptParser();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM