无法在 Nodejs Typescript 应用程序中导入 URL 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46416439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:55:25  来源:igfitidea点击:

Unable to import URL class in Nodejs Typescript app

node.jstypescript

提问by BossmanT

I am trying to import the URL class from the nodejs api so I can parse urls and retrieve their origin, hostname, and paths.

我正在尝试从 nodejs api 导入 URL 类,以便我可以解析 url 并检索它们的来源、主机名和路径。

I am trying to do it by typing import * as URL from "url";

我正在尝试通过键入来做到这一点 import * as URL from "url";

and I have also tried import { URL } from "url";

我也试过 import { URL } from "url";

and I cannot seem to get this to work for me. Any help would be greatly appreciated.

我似乎无法让它对我来说有效。任何帮助将不胜感激。

The way I am trying to use this is as such

我试图使用它的方式是这样的

var site = new URL("http://www.website.com");

var site = new URL("http://www.website.com");

And it is throwing an error because it states that URL is not a constructor

它抛出一个错误,因为它指出 URL 不是构造函数

回答by Saravana

The URL constructorwas introduced as part of node v7.0. import { URL } from "url";is the proper way to import it if you are using node >= v7.0. Make sure you are using the latest version of node typings as updated as well:

URL构造被引入作为节点V7.0的一部分。import { URL } from "url";如果您使用 node >= v7.0,这是导入它的正确方法。确保您使用的是最新版本的节点类型以及更新:

npm install --save-dev @types/node

If your node version is < 7.0 then you can use the parsemethod:

如果您的节点版本 < 7.0,则可以使用以下parse方法:

import * as url from "url";

var site = url.parse("http://www.website.com");

回答by Zbigniew Zagórski

If someone is wondering how to use URLso code is portable between Node.js and browser environment, then i've came to this solution:

如果有人想知道如何使用URL这样的代码在 Node.js 和浏览器环境之间是可移植的,那么我来到了这个解决方案:

import * as nodeUrl from "url";

const URL = typeof window !== "undefined" ? window.URL : nodeUrl.URL;

回答by Phix

import * as url from 'Url';

{ parse: [Function: urlParse],
  resolve: [Function: urlResolve],
  resolveObject: [Function: urlResolveObject],
  format: [Function: urlFormat],
  Url: [Function: Url] 
}

It's not a constructor. You'll need to do use one of the exposed methods:

它不是构造函数。您需要使用公开的方法之一:

import * as url from 'url';

console.log(url.parse('https://www.google.com'))

// Output:
Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.google.com',
  port: null,
  hostname: 'www.google.com',
  hash: null,
  search: null,
  query: null,
  pathname: '/',
  path: '/',
  href: 'https://www.google.com/' }
undefined
>