在使用 moment 构建 angular 8 项目时,我遇到了以下错误消息:
ng build @myproject/common
Error: Cannot call a namespace ('moment')
我在互联网上发现了类似的问题,并提出了以下针对 Angular 6/7 的解决方案。但是它们都不适合我使用角度 8。
更改常规矩导入
import * as moment from 'moment';
自
import * as moment_ from 'moment';
const moment = moment_;
通过 tsconfig.json 编译器选项使用默认导入
import moment from moment;
与tsconfig.json包括
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
......
}
有什么想法可以解决这个问题吗?
吴版
Angular CLI: 8.3.22
Node: 12.13.0
OS: win32 x64
Angular: 8.2.14
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Package Version
------------------------------------------------------------
@angular-devkit/architect 0.803.22
@angular-devkit/build-angular 0.803.22
@angular-devkit/build-ng-packagr 0.803.22
@angular-devkit/build-optimizer 0.803.22
@angular-devkit/build-webpack 0.803.22
@angular-devkit/core 8.3.22
@angular-devkit/schematics 8.3.22
@angular/cdk 8.2.3
@angular/cli 8.3.22
@angular/flex-layout 8.0.0-beta.27
@angular/material 8.2.3
@ngtools/webpack 8.3.22
@schematics/angular 8.3.22
@schematics/update 0.803.22
ng-packagr 5.7.1
rxjs 6.4.0
typescript 3.5.3
webpack 4.39.2
包.json
"dependencies": {
"@angular/animations": "~8.2.9",
"@angular/cdk": "^8.2.3",
"@angular/common": "~8.2.9",
"@angular/compiler": "~8.2.9",
"@angular/core": "^8.2.14",
"@angular/flex-layout": "^8.0.0-beta.27",
"@angular/forms": "~8.2.9",
"@angular/material": "~8.2.2",
"@angular/platform-browser": "~8.2.9",
"@angular/platform-browser-dynamic": "~8.2.9",
"@angular/router": "~8.2.9",
"@rollup/plugin-json": "^4.0.1",
"crypto-js": "^3.1.9-1",
"hammerjs": "^2.0.8",
"moment": "^2.24.0",
"roboto-fontface": "^0.10.0",
"rxjs": "~6.4.0",
"tslib": "^1.10.0",
"typeface-rajdhani": "0.0.72",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.803.8",
"@angular-devkit/build-ng-packagr": "~0.803.8",
"@angular/cli": "^8.3.22",
"@angular/compiler-cli": "~8.2.9",
"@angular/language-service": "~8.2.9",
"@types/crypto-js": "^3.1.43",
"@types/googlemaps": "^3.37.0",
"@types/jasmine": "~3.3.8",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"ng-packagr": "^5.4.0",
"protractor": "~5.4.0",
"rimraf": "^3.0.0",
"ts-node": "~7.0.0",
"tsickle": "^0.37.0",
"tslint": "~5.15.0",
"typescript": "~3.5.3"
}
实际上,第一个解决方法可以解决问题,但我有另一个由主要组件使用 cdk 覆盖调用的角度组件,它也使用错误的时刻导入语义:
所以
import * as moment_ from 'moment';
const moment = moment_;
是 Angular 8 矩导入问题的正确解决方案,如本文主题中所述。
问题解决了。
我在早期版本的 angular 中遇到了类似的问题(也许这会有所帮助(:
"esModuleInterop":true,
在tsconfig.json中。这使您可以仅从CommonJS库中的"库"导入库,而不是从"库"导入*作为库。
如果有人对vite
有这个问题
这是因为你用了import * as something from "something"
你应该使用import something from "something"