Reputation: 65
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'
Upvotes: 4
Views: 2917
Reputation: 5770
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')
Upvotes: 1