我是Angular,Node和Javascript的新手。但我需要在这项技术上开展一些项目。我的问题是这样的。我想在我的项目中使用库i18n-iso-countries。所以我执行了npm install i18n-iso-countries --save
。到目前为止一切都很好。
在我的组件文件home.component.ts
中,我将其导入为:
import * as countries from 'i18n-iso-countries';
并使用这样来确保库已加载并正在运行:
console.log(countries.alpha2ToNumeric("PL"));
console.log(countries.numericToAlpha2(840));
console.log(countries.getName(840, "en"));
console.log(countries.getName("US", "en"));
两条第一行按预期工作,但最后两条没有。我注意到我需要根据文档注册语言环境。那么问题是如何导入语言环境?我需要执行
countries.registerLocale(require("i18n-iso-countries/langs/en.json"));
但错误是:
Cannot find name 'require'.
我还尝试了不同的导入表单,如:
import locale = require('i18n-iso-countries/lang/en.json');
import * as locale from 'i18n-iso-countries/langs/en';
但没有成功。也许我错过了一些微不足道的东西,但我不知道。我阅读了打字稿手册中的Modules
章节,但它没有回答我的问题。也许你们会帮忙。
我的package.json
:
{
"name": "my-app",
"version": "0.1.1",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^4.4.5",
"@angular/cdk": "^2.0.0-beta.12",
"@angular/common": "^4.4.5",
"@angular/compiler": "^4.4.5",
"@angular/core": "^4.4.5",
"@angular/flex-layout": "2.0.0-beta.8",
"@angular/forms": "^4.4.5",
"@angular/http": "^4.4.5",
"@angular/material": "^2.0.0-beta.12",
"@angular/platform-browser": "^4.4.5",
"@angular/platform-browser-dynamic": "^4.4.5",
"@angular/platform-server": "^4.4.5",
"@angular/router": "^4.4.5",
"ag-grid": "^13.3.1",
"ag-grid-angular": "^13.3.0",
"core-js": "2.4.1",
"hammerjs": "2.0.8",
"i18n-iso-countries": "^3.0.0",
"rxjs": "^5.4.1",
"zone.js": "0.8.12"
},
"devDependencies": {
"@angular/cli": "1.1.3",
"@angular/compiler-cli": "^4.4.5",
"@types/hammerjs": "2.0.34",
"@types/jasmine": "2.5.45",
"@types/node": "6.0.78",
"codelyzer": "3.0.1",
"jasmine-core": "2.6.4",
"jasmine-spec-reporter": "4.1.1",
"karma": "1.7.0",
"karma-chrome-launcher": "2.1.1",
"karma-cli": "1.0.1",
"karma-coverage-istanbul-reporter": "1.3.0",
"karma-jasmine": "1.1.0",
"karma-jasmine-html-reporter": "0.2.2",
"protractor": "5.1.2",
"ts-node": "3.0.6",
"tslint": "5.3.2",
"typescript": "^2.3.4"
}
}
答案 0 :(得分:1)
var countries = require("i18n-iso-countries");
// Support french & english languages.
countries.registerLocale(require("i18n-iso-countries/langs/en.json"));
countries.registerLocale(require("i18n-iso-countries/langs/fr.json"));
console.log("US (Alpha-2) => " + countries.getName("US", "en")); // United States of America
console.log("US (Alpha-2) => " + countries.getName("US", "de")); // Vereinigte Staaten von Amerika
console.log("USA (Alpha-3) => " + countries.getName("USA", "en")); // United States of America
console.log("USA (Numeric) => " + countries.getName("840", "en")); // United States of America
答案 1 :(得分:0)
declare var System: any;
declare var require: any;
在word.d.ts中声明这个之后,错误为"要求"和"系统"将不会进入申请..