4

I have an exported module in one file(parser.js) in Typescript project and I did not generate any error during the compilation phase ,but the Compiled file can't work, This makes me feel confused

// parser.d.ts
declare module 'parser' {
    interface Parser {
        parser(url: string):string
    }

    export class UrlParser implements Parser {
        parser(url: string): string  {
            return  url.includes('https') ? url.replace('https', 'http') : '';
        }
    }
}
// parser.js
export default class UrlParser {
    parser(url)  {
        return  url.includes('https') ? url.replace('https', 'http') : '';
    }
}
/// <reference path="../lib/parser.d.ts" />
import * as Parser  from 'parser';

let urlParser = new Parser.UrlParser()
console.log(urlParser.parser('https://www.baidu.com'))
// compiled file I got
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
/// <reference path="../lib/parser.d.ts" />
var Parser = __importStar(require("parser"));
var urlParser = new Parser.UrlParser();
console.log(urlParser.parser('https://www.baidu.com'));

I got an error when I executed the node ./dest/main/js command.

Error: Cannot find module 'parser'
1
  • Can you share how you generated the parser.js? Or maybe package.json regarding ts files? Commented May 15, 2019 at 14:33

1 Answer 1

1

You should use a relative path (e.g. './dest/lib/parser') in that import statement since by default require is going to look in node_modules if a path is not passed (where as TypeScript can be told where 'parser' is).

You could also add a package.json file to the same folder as parser.js with the contents { name: 'parser' } which would allow it to be found via require('parser')

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer,I want to import javascript file in the typescript project with type system. What should I do?
I referenced doc,Did I understand wrong?
It's impossible for me to say whether or not you understood wrong, I'd have to see how your entire project is structured and what your tsconfig looks like. You shouldn't import declaration files, you should import real modules. Change import * as Parser from 'parser' to import Parser from './path/to/parser'; and the import won't fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.