问题
我似乎无法将 MSAL 库正确导入到我的打字稿代码中。我在一个简单的 typescript/react 项目中使用 MSAL for JS 库(应该有类型),该项目使用带有 react-typescript 脚本的 create-react-app 脚手架。我是打字稿的新手,不确定我是否遗漏了一些明显的东西,或者在将它与打字稿项目一起使用时 MSAL 包是否存在问题。
细节:
- 我使用
npm install --save msal
从 NPM 添加了 MSAL 包。 - 我尝试使用不同形式的
import {Msal} from 'msal';
将 MSAL 导入我的 .ts - 这会导致打字稿错误
Could not find a declaration file for module 'msal'. '<path>/node_modules/msal/out/msal.js' implicitly has an 'any' type.
- 认为这很奇怪,我查看了 node_module/msal/out 文件夹并看到了一个“msal.d.ts”文件,这正是我所期望的。
- 当我查看 msal.d.ts 文件的内容时,我没有看到任何我通常希望看到的导出。
- 我尝试使用
npm install --save-dev @types/msal
从@types 安装声明,但它不存在。 - 我还尝试使用
let Msal = require('Msal');
将其导入到我的文件中,但收到 Msal.UserAgentApplication 不是构造函数的错误。 - 我尝试使用 /// 参考指令并向主 index.html 添加脚本标记时运气不佳。这也不是解决问题的正确方法。
例子Msal.ts
import { observable, action, computed } from 'mobx';
import * as Msal from 'msal'; // <-- This line gives the error
class ExampleMsal{
@observable
private _isLoggedIn: boolean;
constructor() {
this._isLoggedIn = false;
}
@computed
get isLoggedIn(): boolean {
return this._isLoggedIn;
}
@action
signIn() {
let userAgentApplication = new Msal.UserAgentApplication('<client-id>', null,
function (errorDes: string, token: string, error: string, tokenType: string) {
// this callback is called after loginRedirect OR acquireTokenRedirect
// (not used for loginPopup/aquireTokenPopup)
}
);
userAgentApplication.loginPopup(['user.read']).then(function(token: string) {
let user = userAgentApplication.getUser();
if (user) {
// signin successful
alert('success');
} else {
// signin failure
alert('fail');
}
}, function (error: string) {
// handle error
alert('Error' + error);
});
this._isLoggedIn = true;
}
@action
signOut() {
this._isLoggedIn = false;
}
}
export default ExampleMsal;
tsconfig.json文件
{
"compilerOptions": {
"outDir": "build/dist",
"module": "commonjs",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"experimentalDecorators": true
},
"exclude": [
"node_modules",
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
],
"types": [
"typePatches"
]
}
原文由 nbrowne 发布,翻译遵循 CC BY-SA 4.0 许可协议
正如您正确提到的那样 - 在 msal.d.ts 中没有导出 - 它不是模块,因此您不应该尝试导入。
相反,您可以这样使用它:
请注意,即使在自述文件中,他们也只指定了一种使用其库的方式——通过包含脚本标签,而不是通过导入模块。进一步查看他们的源代码表明他们也没有使用模块。