使用 Microsoft Graph 工具包构建 SharePoint Web 部件
本文介绍如何在 SharePoint 客户端 Web 部件中使用 Microsoft Graph 工具包组件。 开始使用涉及以下步骤:
- 设置开发环境。
- 创建 Web 部件项目。
- 添加 Microsoft Graph 工具包包。
- 添加 SharePoint 提供程序。
- 添加组件。
- 配置权限。
- 配置 webpack
- 构建和部署 Web 部件。
- 测试 Web 部件。
设置 SharePoint 框架开发环境并创建新的 Web 部件
按照设置SharePoint 框架开发环境的步骤进行操作。
创建 Web 部件项目
按照说明 创建新的 Web 部件。 当被问及要使用哪个模板时,请选择“React”。
重要
在使用 yo @microsoft/sharepoint
时选择框架时,必须选择React。
添加 Microsoft Graph 工具包包
Microsoft Graph 工具包发布生成SharePoint 框架 Web 部件所需的多个包。 安装 @microsoft/mgt-element
、 @microsoft/mgt-react
、 @microsoft/mgt-sharepoint-provider
和 @microsoft/mgt-spfx-utils
包会安装必要的依赖项。
npm install @microsoft/mgt-element @microsoft/mgt-react @microsoft/mgt-sharepoint-provider @microsoft/mgt-spfx-utils
添加 SharePoint 提供程序
Microsoft Graph 工具包提供程序为组件启用身份验证和对 Microsoft Graph 的访问。 若要了解详细信息,请参阅使用提供程序。 SharePoint Web 部件始终存在于经过身份验证的上下文中,因为用户经过身份验证才能访问托管 Web 部件的页面。 使用此上下文初始化 SharePoint 提供程序。
首先,将提供程序添加到 Web 部件。 在项目文件夹中找到 src\webparts\<your-project>\<your-web-part>.ts
文件,并将以下行添加到文件顶部,位于现有 import
语句的正下方:
import { Providers } from "@microsoft/mgt-element";
import { SharePointProvider } from "@microsoft/mgt-sharepoint-provider";
接下来,在 Web 部件的 方法内 onInit()
使用经过身份验证的上下文初始化提供程序。 在同一文件中,在 public render(): void {
行之前添加以下代码:
protected async onInit() {
if (!Providers.globalProvider) {
Providers.globalProvider = new SharePointProvider(this.context);
}
}
设置消除歧义
若要确保在单个页面中有多个使用 Microsoft Graph Toolkit 的 Web 部件解决方案时 Web 部件正常工作,必须使用消除歧义。 有关详细信息,请参阅 消除歧义。
首先,从 @microsoft/mgt-element
更新导入,并为 lazyLoadComponent
帮助程序添加一个导入项。
import { Providers, customElementHelper } from "@microsoft/mgt-element";
import { lazyLoadComponent } from "@microsoft/mgt-spfx-utils";
接下来,更新 onInit()
根 Web 部件的 方法以设置消除歧义。 用于消除歧义的字符串对于SharePoint 框架解决方案必须是唯一的:
protected async onInit(): Promise<void> {
if (!Providers.globalProvider) {
Providers.globalProvider = new SharePointProvider(this.context);
}
customElementHelper.withDisambiguation('contoso-hr-solution');
return super.onInit();
}
更新 React 组件的导入和呈现
首先,将组件的导入转换为使用 React.lazy
。 找到 语句 import <WebPartName> from './components/<WebPartName>;
并将其更新为以下内容:
const MgtComponent = React.lazy(
() =>
import(
/* webpackChunkName: 'mgt-react-component' */ "./components/<WebPartName>"
)
);
接下来,修改 render 方法以 lazyLoadComponent
使用帮助程序:
public render(): void {
const element = lazyLoadComponent<IHelloWorldProps>(MgtComponent, {
description: this.properties.description,
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userDisplayName: this.context.pageContext.user.displayName
});
ReactDom.render(element, this.domElement);
}
现在,Web 部件应如下所示:
import * as React from "react";
import * as ReactDom from "react-dom";
import { Version } from "@microsoft/sp-core-library";
import {
type IPropertyPaneConfiguration,
PropertyPaneTextField,
} from "@microsoft/sp-property-pane";
import { BaseClientSideWebPart } from "@microsoft/sp-webpart-base";
import { IReadonlyTheme } from "@microsoft/sp-component-base";
import { Providers, customElementHelper } from "@microsoft/mgt-element";
import { lazyLoadComponent } from "@microsoft/mgt-spfx-utils";
import { SharePointProvider } from "@microsoft/mgt-sharepoint-provider";
import * as strings from "HelloWorldWebPartStrings";
const HelloWorld = React.lazy(
() =>
import(
/* webpackChunkName: 'mgt-react-component' */ "./components/HelloWorld"
)
);
import { IHelloWorldProps } from "./components/IHelloWorldProps";
export interface IHelloWorldWebPartProps {
description: string;
}
export default class HelloWorldWebPart extends BaseClientSideWebPart<IHelloWorldWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = "";
public render(): void {
const element = lazyLoadComponent<IHelloWorldProps>(HelloWorld, {
description: this.properties.description,
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userDisplayName: this.context.pageContext.user.displayName,
});
ReactDom.render(element, this.domElement);
}
protected async onInit(): Promise<void> {
if (!Providers.globalProvider) {
Providers.globalProvider = new SharePointProvider(this.context);
}
customElementHelper.withDisambiguation("contoso-hr-solution");
return super.onInit();
}
// [...] trimmed for brevity
}
添加组件
将组件添加到 React 组件。 找到并打开 src\webparts\<your-project>\components\<your-component>.tsx
文件并添加要使用的组件(在本例 Person
中为组件)的导入,然后将 方法更新 render()
为使用 Person 组件。 现在,组件应如下所示:
import * as React from "react";
import type { IHelloWorldProps } from "./IHelloWorldProps";
import { Person } from "@microsoft/mgt-react";
export default class HelloWorld extends React.Component<IHelloWorldProps, {}> {
public render(): React.ReactElement<IHelloWorldProps> {
return <Person personQuery="me" view="twolines" />;
}
}
或者,如果希望使用React功能组件:
import * as React from "react";
import type { IHelloWorldProps } from "./IHelloWorldProps";
import { Person, ViewType } from "@microsoft/mgt-react";
const HelloWorld = (props: IHelloWorldProps): React.ReactElement => (
<Person personQuery="me" view={ViewType.twolines} />
);
export default HelloWorld;
配置权限
若要从 SharePoint 框架应用程序调用 Microsoft Graph,你需要在解决方案包中请求所需的权限,Microsoft 365 租户管理员需要批准请求的权限。
若要将权限添加到解决方案包,请找到并打开 config\package-solution.json
文件,然后设置:
"isDomainIsolated": false,
在该行正下方,添加以下行:
"webApiPermissionRequests":[],
确定所需的Microsoft图形 API权限取决于所使用的组件。 每个组件的文档页都提供组件所需的权限列表。 需要向 添加每个所需的权限 webApiPermissionRequests
。 例如,如果使用的是“人员”组件和“日程”组件,则 webApiPermissionRequests
可能如下所示:
"webApiPermissionRequests": [
{
"resource": "Microsoft Graph",
"scope": "User.Read"
},
{
"resource": "Microsoft Graph",
"scope": "Calendars.Read"
}
]
配置 webpack
为了生成 Web 部件,必须更新SharePoint 框架 webpack 配置,以便通过可选的链接和通过其他 Babel 转换的 null 合并来正确处理新式 JavaScript。
安装 Babel 包
若要正确处理发出基于 ES2021 的代码的依赖项,需要将 babel 加载器和某些转换作为开发依赖项添加到项目中。
npm i --save-dev babel-loader@8.3.0 @babel/plugin-transform-optional-chaining @babel/plugin-transform-nullish-coalescing-operator @babel/plugin-transform-logical-assignment-operators
修改 Webpack 配置
Webpack 版本 <=4
SharePoint 框架提供了一个扩展性模型,用于修改用于捆绑 Web 部件的 Webpack 配置。 找到并打开 gulpfile.js
。 在包含的行上方添加以下代码 build.initialize(require('gulp'));
const path = require("path");
const litFolders = [
`node_modules${path.sep}lit${path.sep}`,
`node_modules${path.sep}@lit${path.sep}`,
`node_modules${path.sep}lit-html${path.sep}`
];
build.configureWebpack.mergeConfig({
additionalConfiguration: generatedConfiguration => {
generatedConfiguration.module.rules.push({
test: /\.js$/,
// only run on lit packages
include: resourcePath =>
litFolders.some(litFolder => resourcePath.includes(litFolder)),
use: {
loader: 'babel-loader',
options: {
plugins: [
'@babel/plugin-transform-optional-chaining',
'@babel/plugin-transform-nullish-coalescing-operator',
'@babel/plugin-transform-logical-assignment-operators'
]
}
}
});
return generatedConfiguration;
}
});
这可确保SharePoint 框架生成链正确处理库中的代码lit
。 这是 SharePoint 提供程序版本 <=v1.18
所必需的。
Webpack 版本 5+
使用 Webpack 版本 5+ 时,无需进行其他配置。 SharePoint 提供程序版本 v1.19+
支持此操作。
构建和部署 Web 部件
现在,你将生成应用程序并将其部署到 SharePoint。 通过运行以下命令构建应用程序:
gulp build
gulp bundle
gulp package-solution
文件夹中 sharepoint/solution
有一个新 .sppkg
文件。 需要将此文件上传到 SharePoint Online 应用程序目录。 转到 SharePoint 管理中心的“更多功能”页面。 在“应用程序”下选择“打开”,然后选择“应用程序目录”,然后选择“分发 SharePoint 应用”。
.sppkg
上传文件,然后选择“部署”。
接下来,需要以管理员身份批准权限。
转到 SharePoint 管理中心。 在左侧导航中,选择“高级”,然后选择“API 访问”。 你应该会看到你在 config\package-solution.json
文件中添加的每个权限的待处理请求。 选择并批准每个权限。
测试 Web 部件
现在可以将 Web 部件添加到 SharePoint 页面并对其进行测试。需要使用托管的工作台来测试使用 Microsoft Graph 工具包的 Web 部件,因为这些组件需要经过身份验证的上下文才能调用 Microsoft Graph。 可以在 https:// YOUR_TENANT.sharepoint.com/_layouts/15/workbench.aspx<> 找到托管工作台。
打开项目中的 config\serve.json
文件,将 的值 initialPage
替换为托管工作台的 URL:
"initialPage": "https://<YOUR_TENANT>.sharepoint.com/_layouts/15/workbench.aspx",
保存文件,然后在控制台中运行以下命令来构建和预览 Web 部件:
gulp serve
托管的工作台会自动在浏览器中打开。 将 Web 部件添加到页面,你应该会看到带有 Microsoft Graph 工具包组件的 Web 部件正在运行! 只要 gulp serve 命令仍在控制台中运行,你就可以继续编辑代码,然后刷新浏览器以查看更改。
后续步骤
- 查看有关 生成 SharePoint Web 部件的分步教程。
- 在样本中试用组件。
- 在 Stack Overflow 上提问。
- 在 GitHub 上报告 bug 或提出功能请求。