[英]How to load XRegExp in Angular2
我想在用TypeScript编写的Angular2应用程序中使用XRegExp库。
我已经将XRegExp安装为node.js模块。
如何获取var unicodeWord = XRegExp("^\\\\pL+$");
在组件方法中工作?
(如何在TypeScript中引用JS库?如何在angular中加载node.js模块?)
更新
Types.json:
{
"ambientDependencies": {
"es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2",
"jasmine": "github:DefinitelyTyped/DefinitelyTyped/jasmine/jasmine.d.ts#d594ef506d1efe2fea15f8f39099d19b39436b71",
"xregexp": "github:DefinitelyTyped/DefinitelyTyped/xregexp/xregexp.d.ts"
}
}
我的index.html中的<head>
标记:
<head>
<title>Amadeus</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 1. Load libraries -->
<!-- IE required polyfills, in this exact order -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.js"></script>
<!-- 2. Configure SystemJS -->
<script>
System.config({
paths: {
xregexp: 'node_modules/xregexp/src/xregexp.js'
},
packages: {
angular_components: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('angular_components/ignition')
.then(null, console.error.bind(console));
</script>
</head>
点火:
import {bootstrap} from 'angular2/platform/browser'
import {AmadeusComponent} from './amadeus/amadeus.component'
bootstrap(AmadeusComponent);
amadeus.component.ts:
import {Component} from 'angular2/core';
import {XRegExp} from 'xregexp';
@Component({
selector: 'amadeus',
templateUrl: 'angular_components/amadeus/amadeus.component.ahtml'
})
export class AmadeusComponent {
constructor(){
console.log(XRegExp); // undefined
}
}
您可以通过以下方式执行此操作:
在您的package.json中,将'typings'添加为dev依赖项,并(可选)后安装操作:
"devDependencies":
{
"typings": "latest"
},
"scripts":
{
"postinstall": "typings install --save"
}
将具有以下内容的Types.json文件添加到您的根文件夹中:
{
"ambientDependencies": {
"xregexp": "github:DefinitelyTyped/DefinitelyTyped/xregexp/xregexp.d.ts"
}
}
然后在控制台中导航到项目根目录(package.json,tsconfig.json等所在的位置)并运行
npm安装
这将为您提供xregexp库的打字稿定义。
不要忘记使用tsconfig文件中的exclude部分来排除浏览器(或主要)定义,如下所示:
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"module": "commonjs",
"target": "es6",
"sourceMap": true,
"outDir": "bin",
"declaration": true
},
"exclude": [
"node_modules",
"typings/browser.d.ts",
"typings/browser/**"
]
}
在您的systemjs配置中:
System.config({
paths: {
xregexp: 'path/to/xregexp.js'
}
});
System.defaultJSExtensions = true;
然后使用它:
import XRegExp = require('xregexp');
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.