我正在尝试使用angular4 + typescript导入add
lodash
方法。
我尝试过很多不同的东西:
import { add } from 'lodash';
import { add } from 'lodash/add';
import * as add from 'lodash/add';
import { add } from 'lodash.add';
import * as add from 'lodash.add';
(和我忘记的其他人)
这是最新(desesperate?)尝试实现此目的:
import { Component, OnInit } from '@angular/core';
import add = require('lodash.add');
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
private x: number;
constructor() { }
ngOnInit() {
let y = add(5, 5);
}
}
但它不起作用。
当我“服务”时,我收到消息:
错误在... test.component.ts(2,1):在定位ECMAScript 2015模块时无法使用导入分配。考虑使用'import *来自“mod”的ns,'import {a}来自“mod”','import d from“mod”'或其他模块格式。)
我的包配置:
{
"name": "treeshake",
"version": "0.0.0",
"license": "MIT",
"angular-cli": {},
"scripts": {
"ng": "ng",
"start": "ng serve",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/common": "^2.4.0",
"@angular/compiler": "^2.4.0",
"@angular/core": "^2.4.0",
"@angular/forms": "^2.4.0",
"@angular/http": "^2.4.0",
"@angular/platform-browser": "^2.4.0",
"@angular/platform-browser-dynamic": "^2.4.0",
"@angular/router": "^3.4.0",
"@types/lodash": "lattest",
"@types/lodash.add": "^3.7.2",
"core-js": "^2.4.1",
"lodash": "^4.17.4",
"lodash.add": "^3.7.0",
"rxjs": "^5.4.2",
"zone.js": "^0.7.6"
},
"devDependencies": {
"@angular/cli": "1.0.0-beta.32.3",
"@angular/compiler-cli": "^2.4.0",
"@types/jasmine": "2.5.38",
"@types/node": "~6.0.60",
"codelyzer": "~2.0.0-beta.4",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.0.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^0.2.0",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.0",
"ts-node": "~2.0.0",
"tslint": "~4.4.2",
"typescript": "^2.4.1"
}
}
和我的tsconfig.json
{
"compilerOptions": {
"baseUrl": "",
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"es2016",
"dom"
],
"mapRoot": "./",
"module": "es2015",
"moduleResolution": "node",
"outDir": "../dist/out-tsc",
"sourceMap": true,
"target": "es5",
"typeRoots": [
"../node_modules/@types"
]
}
}
答案 0 :(得分:3)
我建议使用lodash-es
,它是一个相同的lodash,但作为单独的ECMA脚本模块与每个函数一起分发。然后只导入add
函数所需的代码:
import add from 'lodash-es/add'
请注意,它还有自己的@types/lodash-es
包,而不是@types/lodash
。
答案 1 :(得分:1)
您在package.json
中的版本是错误的。纠正错字
@types/lodash": "lattest",
您应该将lodash导入为
import * as _ from 'lodash';
确保您在typings.json文件中列出了lodash
更新1:
使用
全局安装typings
npm install typings -g
然后通过打字输入lodash
typings install lodash --save
将导入语句用作
import { add } from 'lodash';