typescript 如何将 MSAL(用于 js 的 Microsoft 身份验证库)正确导入和使用到打字稿反应单页应用程序中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44228493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:35:32  来源:igfitidea点击:

How to properly import and use the MSAL (Microsoft Authentication Library for js) into a typescript react single page application?

javascripttypescripttypescript-typingsmsal

提问by nbrowne

Problem

问题

I can't seem to get the MSAL library to import properly into my typescript code. I'm using the MSAL for JSlibrary (which is supposed to have typings) in a simple typescript/react project scaffolded using the create-react-app with react-typescript scripts. I'm new to typescript and not sure if I'm missing something obvious or if there is a problem with the MSAL package when using it with typescript projects.

我似乎无法将 MSAL 库正确导入到我的打字稿代码中。我在一个简单的打字稿/反应项目中使用MSAL for JS库(应该有类型),该项目使用 create-react-app 和 react-typescript 脚本搭建。我是打字稿的新手,不确定我是否遗漏了一些明显的东西,或者在将 MSAL 包与打字稿项目一起使用时是否存在问题。

Details:

细节:

  1. I added the MSAL package from NPM using npm install --save msal.
  2. I attempted to import the MSAL into my .ts using different forms of import {Msal} from 'msal';
  3. This results in a typescript error Could not find a declaration file for module 'msal'. '<path>/node_modules/msal/out/msal.js' implicitly has an 'any' type.
  4. Thinking that was odd, I looked at the the node_module/msal/out folder and saw a 'msal.d.ts' file, which is what I would expect.
  5. When I look at the contents of the msal.d.tsfile, I don't see any exports, which I would normally expect to see.
  6. I tried install the declaration from @types using npm install --save-dev @types/msal, but it doesn't exist.
  7. I also tried importing it into my file using let Msal = require('Msal');, but get an error that the Msal.UserAgentApplication isn't a constructor.
  8. I didn't have much luck trying to use the /// reference directive and adding a script tag to the main index.html. This also doesn't feel like the right way to solve the problem.
  1. 我使用npm install --save msal.
  2. 我尝试使用不同形式的 import {Msal} from 'msal';
  3. 这会导致打字稿错误 Could not find a declaration file for module 'msal'. '<path>/node_modules/msal/out/msal.js' implicitly has an 'any' type.
  4. 认为这很奇怪,我查看了 node_module/msal/out 文件夹并看到了一个“msal.d.ts”文件,这正是我所期望的。
  5. 当我查看msal.d.ts文件的内容时,我没有看到任何我通常希望看到的导出。
  6. 我尝试使用从@types 安装声明npm install --save-dev @types/msal,但它不存在。
  7. 我还尝试使用 将其导入到我的文件中let Msal = require('Msal');,但得到一个错误,即 Msal.UserAgentApplication 不是构造函数。
  8. 我在尝试使用 /// 引用指令并将脚本标记添加到主 index.html 时运气不佳。这也不是解决问题的正确方法。

ExampleMsal.ts

示例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"
  ]
}

采纳答案by Amid

As you have correctly mentioned - in the msal.d.ts there are no exports - its not a module, and therefore you should not try importing.

正如您正确提到的 - 在 msal.d.ts 中没有导出 - 它不是模块,因此您不应该尝试导入。

Instead you can use it like this:

相反,您可以像这样使用它:

/// <reference path="./node_modules/msal/out/msal.d.ts" />

const userAgentApplication = new Msal.UserAgentApplication("your_client_id", null, (errorDes, token, error, tokenType) =>
    {

    });

Note that even in readme they specify only one way of using their library - by including script tag, not by importing module. And further looking into their source code shows they are not using modules as well.

请注意,即使在自述文件中,他们也仅指定了一种使用其库的方式 - 通过包含脚本标记,而不是通过导入模块。进一步查看他们的源代码表明他们也没有使用模块。

回答by Henry Daehnke

It looks like the latest version of MSAL.js doeshave a CommonJS export. You can now just do the following in TypeScript (tested with version 2.3.3 of TypeScript and 0.1.3 of MSAL.js):

看起来最新版本的 MSAL.js确实有一个 CommonJS 导出。您现在可以在 TypeScript 中执行以下操作(使用 TypeScript 2.3.3 版和 MSAL.js 0.1.3 版测试):

import * as Msal from 'msal';

Now in your .ts(or in my case .tsxfile) you can, for instance, setup a click event handler and create a UserAgentApplication object:

现在,在您的.ts(或在我的案例.tsx文件中)中,您可以设置一个单击事件处理程序并创建一个 UserAgentApplication 对象:

// In you class somewhere
private userAgentApplication: any = undefined;

// The login button click handler
handleLoginClick = (event: any): void => {
    if (!this.userAgentApplication) {
        this.userAgentApplication = new Msal.UserAgentApplication(
            'clientID string', 'authority string or empty', this.authCallback, { cacheLocation: 'localStorage'});
    }
    // Other login stuff...
}

// In React render()
public render() {
    return (
        <Button
            bsStyle="warning"
            type="button"
            onClick={(e) => this.handleLoginClick(e)}
        >
        Log in
        </Button>
    );
}

回答by Ali Malekpour

I had the same issue and couldn't wait for the author to fix it, so forked and modified the original code. Just as a temporary fix you can use my version msalxinstead of msal.

我也遇到了同样的问题,迫不及待地等作者修复了,所以fork并修改了原代码。作为临时修复,您可以使用我的版本msalx而不是msal.

npm install msalx

npm install msalx

You can find the source code and an example usage in react at: https://github.com/malekpour/microsoft-authentication-library-for-js#example

您可以在 react 中找到源代码和示例用法:https: //github.com/malekpour/microsoft-authentication-library-for-js#example

回答by Kyle Reed

If you install the exports-loader (npm install exports-loader --save-dev) you can avoid the script tag and add the following to your directives:

如果你安装了exports-loader ( npm install exports-loader --save-dev) 你可以避免使用脚本标签并将以下内容添加到你的指令中:

var Msal = require("exports-loader?Msal!../../../node_modules/msal/out/msal.js"); 

回答by vzhikness

As stated in wikiproper way to import is:

正如维基中所述,正确的导入方法是:

import * as Msal from 'msal';