简体   繁体   English

使用TypeScript,Angular 2和SystemJS导入节点模块

[英]Importing node modules with TypeScript, Angular 2 and SystemJS

I am writing a basic Angular 2 app. 我正在编写一个基本的Angular 2应用程序。 I am creating a class User that has a function validPassword() that uses bcrypt to validate a password: 我正在创建一个类User ,该类具有一个功能validPassword() ,该函数使用bcrypt来验证密码:

import { compareSync, genSaltSync, hashSync } from 'bcrypt';
import { Document, Schema, model } from 'mongoose';

export class User {
  username: string;
  password: string;

  isValidPassword(password: string): boolean {
    return compareSync(password, this.password)
  }
}

let userSchema = new Schema({
  username: { required: true, type: String },
  password: { required: true, type: String }
}, { timestamps: true });

userSchema.pre('save', function (next) {
  this.password = hashSync(this.password, genSaltSync(8));
  next();
});

export interface UserDocument extends User, Document {}

export const Users = model<UserDocument>('User', userSchema);

As you see, I am using the bcrypt and mongoose npm packages. 如您所见,我正在使用bcryptmongoose npm软件包。

My SystemJS is configured as follows: 我的SystemJS配置如下:

(function (global) {
  System.config({
    map: {
      '@angular': 'node_modules/@angular',
      'bcrypt': 'node_modules/bcrypt',
      'bindings': 'node_modules/bindings',
      'mongoose': 'node_modules/mongoose',
      'rxjs': 'node_modules/rxjs'
    },
    paths: {
      'node_modules/@angular/*': 'node_modules/@angular/*/bundles'
    },
    meta: {
      '@angular/*': {'format': 'cjs'}
    },
    packages: {
      'src': {main: 'main', defaultExtension: 'js'},
      '@angular/core': {main: 'core.umd.min.js'},
      '@angular/common': {main: 'common.umd.min.js'},
      '@angular/compiler': {main: 'compiler.umd.min.js'},
      '@angular/forms': {main: 'forms.umd.min.js'},
      '@angular/http': {main: 'http.umd.min.js'},
      '@angular/platform-browser': {main: 'platform-browser.umd.min.js'},
      '@angular/platform-browser-dynamic': {main:'platform-browser-dynamic.umd.min.js'},
      'bcrypt': {main: 'bCrypt.js'},
      'mongoose': {main: 'index.js'},
      'rxjs': {defaultExtension: 'js'}
    }
  });
}(this));

My typings dependencies are: 我的打字依赖性是:

{
  "globalDependencies": {
    "bcrypt": "registry:dt/bcrypt#0.0.0+20160316155526",
    "core-js": "registry:dt/core-js#0.0.0+20160914114559",
    "jasmine": "registry:dt/jasmine#2.5.0+20161003201800",
    "mongodb": "registry:dt/mongodb#2.1.0+20160602142941",
    "mongoose": "registry:dt/mongoose#4.5.9+20161010180758",
    "node": "registry:dt/node#6.0.0+20161014191813"
  }
}

My tsconfig is as follows: 我的tsconfig如下:

{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  }
}

When I go to run the project, the following errors display in the console: 当我去运行项目时,控制台中显示以下错误:

1274 GET http://localhost:8080/crypto 404 (Not Found)
http://localhost:8080/node_modules/mongoose/lib.js 404 (Not Found)
http://localhost:8080/node_modules/bindings/ 404 (Not Found)

I understand this is a SystemJS issue. 我了解这是SystemJS问题。 When I go to add, say, 当我添加时,说

'bindings': 'node_modules/bindings'

to the map object and, 到地图对象,然后

'bindings': {main: 'bindings.js'},

to the packages object in SystemJS, I get a whole new set of errors (cannot find fs and path). 到SystemJS中的packages对象,我得到了一套全新的错误(找不到fs和路径)。

Should I be manually adding all missing package paths each time I install a new package? 每次安装新软件包时,是否应该手动添加所有缺少的软件包路径? Is there a better way to do this? 有一个更好的方法吗?

I recently had the same issue when bundling my server-side into one file with SystemJS. 最近,使用SystemJS将服务器端绑定到一个文件中时,我遇到了同样的问题。 The problem, at least with mongoose (and I suspect the others), is that SystemJS does not support node extension format so it doesn't understand to look for index.js inside the "./lib" folder. 至少对于猫鼬(我怀疑其他人),问题在于SystemJS不支持节点扩展格式,因此无法理解在“ ./lib”文件夹中查找index.js。 And even if you add "mongoose/lib" to your System.config, mongoose depends on a slew of node modules that would require an obnoxious amount of mapping in your System.config.package.mongoose to compensate. 即使您在System.config中添加“ mongoose / lib”,猫鼬也取决于大量的节点模块,这需要在System.config.package.mongoose中进行大量映射,以进行补偿。

A solution that I've found is to create a new System module and set it to the "package" that you need, above your System.config. 我找到的解决方案是创建一个新的System模块,并将其设置为System.config上方所需的“包”。

System.set('package', System.newModule({
  default: require('package') 
}));

Unfortunately if you're using typescript your import statements require your "package" to have a type. 不幸的是,如果您使用的是Typescript,则导入语句要求您的“包”具有类型。 These are basically just a set of interfaces and abstract classes so that your entire typescript project can understand the "package" library has functions, classes, etc... 这些基本上只是一组接口和抽象类,因此您的整个打字稿项目都可以理解“包”库中包含的函数,类等。

But some package types, like mongoose, do not have a default export. 但是某些包类型(例如猫鼬)没有默认导出。 So if you set the mongoose module like above and import like below.. 因此,如果您像上面那样设置猫鼬模块,并像下面那样导入。

import mongoose from 'mongoose';

you are sure to get either transpiler or IDE typescript errors because as said above the typings type does not have a corresponding default export. 您一定会遇到transpiler或IDE打字稿错误,因为如上所述,打字类型没有相应的默认导出。

To fix this just set allowSyntheticDefaultImports option to true in your tsconfig.json 要解决此问题,只需在tsconfig.json中将allowSyntheticDefaultImports选项设置为true即可

Hope this helps :) 希望这可以帮助 :)

I was stuck with the same problem for some time, and I was using Angular-cli so guess no SystemJs involved. 一段时间以来,我一直遇到相同的问题,并且我使用的是Angular-cli,所以猜想其中没有SystemJ。 I was trying to load 'diff' node module, and following worked for me: 我正在尝试加载“ diff”节点模块,以下对我有用:

import * as JsDiff from 'diff';

Source: https://medium.com/@s_eschweiler/using-external-libraries-with-angular-2-87e06db8e5d1 资料来源: https : //medium.com/@s_eschweiler/using-external-libraries-with-angular-2-87e06db8e5d1

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM