Create HelloWorld WebPart in the new SharePoint Framework
Objective
In this lab, you will build a SharePoint client-side web part.Scenario
Client-side web parts are client-side components that run inside the context of a SharePoint page. Client-side web parts can be deployed to SharePoint Online, and you can also use modern JavaScript tools and libraries to build them.
Client-side web parts support:
•Building with HTML and JavaScript.
•Both SharePoint online and on-premises environments.
•Building with HTML and JavaScript.
•Both SharePoint online and on-premises environments.
Note: The SharePoint Framework is currently in preview and is subject to change. SharePoint Framework client-side web parts are not currently supported for use in production environments.
Virtual Machines
- QSC 1511 Master
Exercise 1 : Create a new web part project
In this exercise, you will create a new web part project.
- Sign in to the virtual machineSign in to the virtual machine using Developer as the username and P@ssw0rd! as the password.
You can find the credentials needed for this lab on the Content tab in the lab environment. - Open a Command Prompt windowIn the Search bar, type cmd, and then press Enter.
- Create a project folderAt the command prompt, type md helloworld-webpart.
- Change to the project folderAt the command prompt, type cd helloworld-webpart.
- Run the Yeoman SharePoint GeneratorCreate a new HelloWorld web part by running the Yeoman SharePoint Generator. At the command prompt, type yo @microsoft/sharepoint.
- Accept the default helloworld-webpartWhen prompted, accept the default helloworld-webpart as your solution name and choose Enter.
- Place files in the current folderSelect Use the current folder for where to place the files.
- Set the web part nameAccept the default HelloWorld as your web part name and choose Enter.
- Accept the default descriptionAccept the default HelloWorld description as your web part description and choose Enter.
- Accept the default No javascript web frameworkAccept the default No javascript web framework as the framework you would like to use and choose Enter.At this point, Yeoman will install the required dependencies and scaffold the solution files along with the HelloWorld web part. This might take a few minutes.
- Review the scaffold completion messageWhen the scaffold is complete, you should see the message shown in the Screenshot indicating a successful scaffold.For information about known issues, see http://dev.office.com/sharepoint/docs/spfx/web-parts/basics/known-issues.
- Close Command Prompt WindowClose Command Prompt Window.
You have now created a new web part project.
Exercise 2 : Preview the web part
In this exercise,you will preview your web part, build and run it on a local web server.
- Open new Command Prompt windowOpen new Command Prompt window.
- At the command prompt, type cd helloworld-webpartAt the command prompt, type cd helloworld-webpart
- Run gulp serve to build and preview the web partMake sure you are still in the helloworld-webpart directory and enter the command gulp serve to build and preview your web part:
The client-side toolchain uses HTTPS endpoint by default. However, since a default certificate is not configured for the local dev environment, your browser will report a certificate error. Depending on the browser you are using, you may need to add exception (for example, Mozilla Firefox) or click Advanced and select to proceed to the website (for example, Microsoft Edge or Google Chrome).This command will execute a series of gulp tasks to create a local, Node-based HTTPS server on 'localhost:4321' and launch your default browser to preview web parts from your local dev environment. - Review gulpSharePoint client-side development tools use gulp as the task runner to handle build process tasks such as those shown in the Knowledge [Bulb in head] window.
You can access gulp at http://gulpjs.com/.- Bundle and minify JavaScript and CSS files.
- Run tools to call the bundling and minification tasks before each build.
- Compile SASS files to CSS.
- Compile TypeScript files to JavaScript.
If you are new to gulp, you can read Using Gulp which describes using gulp with Visual Studio in conjunction with building ASP.NET 5 projects.
Visual Studio Code provides built-in support for gulp and other task runners. Choose Ctrl+Shift+B on Windows or Cmd+Shift+B on Mac to debug and preview your web part. - Click the + to open the toolboxTo add the HelloWorld web part, choose the add (+) button to open the toolbox
The add button opens the toolbox where you can see a list of web parts available for you to add. The list will include the HelloWorld web part as well other web parts available locally in your development environment.SharePoint workbench is a developer design surface that enables you to quickly preview and test web parts without deploying them in SharePoint. SharePoint workbench includes the client-side page and the client-side canvas in which you can add, delete and test your web parts in development. - Choose HelloWorld to add the web part to the pageChoose HelloWorld to add the web part to the page
- View the web partView the web part on the page.
Congratulations! You have just added your first client-side web part to a client-side page. - View the web part property paneNow, choose the pencil icon on the far left of the web part to reveal the web part property pane.The property pane is where you can define properties to customize your web part. The property pane is client-side driven and provides a consistent design across SharePoint.
- Modify the description textModify the text in the Description text box to Client-side web parts are awesome!Notice how the text in the web part also changes as you type.
One of the new capabilities available to the property pane is to configure its update behavior, which can be set to reactive or non-reactive. By default the update behavior is reactive and enables you to see the changes as you edit the properties. The changes are saved instantly as when the behavior is reactive.
You have now previewed your web part, built and run it on a local web server.
Exercise 3 : Web part project structure
You can use Visual Studio Code to explore the web part project structure.
Because the SharePoint client-side solution is HTML/TypeScript based, you can use any code editor or IDE that supports client-side development to build your web part, such as:
Because the SharePoint client-side solution is HTML/TypeScript based, you can use any code editor or IDE that supports client-side development to build your web part, such as:
- Visual Studio Code
- Sublime
- Atom
- Webstorm
Using Visual Studio 2015
Currently, support for SharePoint client-side projects in Visual Studio is available through NodeJS Tools for Visual Studio.
- Change to the src\webparts\helloWorld folderAt the command prompt, go to the src\webparts\helloWorld directory.Make sure you are in the C:\Users\Developer\helloworld-webpart folder.
- Enter the command codeEnter the command code . (please note: code "dot") to open the web part project in Visual Studio Code.Make sure you enter the command code . including the .
- Review the Web part classHelloWorldWebPart.ts defines the main entry point for the web part. The web part class HelloWorldWebPart extends the BaseClientSideWebPart. Any client-side web part should extend the BaseClientSideWebPart class in order to be defined as a valid web part.public constructor(context: IWebPartContext) {
super(context);
}
TypeScript is the primary language for building SharePoint client-side web parts. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. SharePoint client-side development tools are built using TypeScript classes, modules, and interfaces to help developers build robust client-side web parts. - Review property type IHelloWorldWebPartPropsBaseClientSideWebPart implements the minimal functionality that is required to build a web part. This class also provides many parameters to validate and access to read-only properties such as displayMode, web part properties, web part context, web part instanceId, the web part domElement and much more.
Notice that the web part class is defined to accept a property type IHelloWorldWebPartProps.
The property type is defined as an interface in a separate file IHelloWorldWebPartProps.ts.export interface IHelloWorldWebPartProps {
description: string;
}
This property definition is used to define custom property types for your web part, which is described in the property pane section later. - Review the web part render methodThe DOM element where the web part should be rendered is available in the render method. This method is used to render the web part inside that DOM element.In the HelloWorld web part, the DOM element is set to a DIV. The method parameters include the display mode (either Read or Edit) and the configured web part properties if any.
public render(): void {
this.domElement.innerHTML = `
Welcome to SharePoint!
Customize SharePoint experiences using Web Parts.
${this.properties.description}
Learn more
} - Review how you would load a React componentThis model is flexible enough so that web parts can be built in any JavaScript framework and loaded into the DOM element. The Knowledge [Bulb in head] window shows an example of how you would load a React component instead of plain HTML.render(): void {
let e = React.createElement(TodoComponent, this.properties);
ReactDom.render(e, this.domElement);
}
Note: The Yeoman SharePoint generator lets you choose React as your framework of choice when adding a new web part to the project. - Configure the Web part property paneThe property pane is also defined in the HelloWorldWebPart class. The propertyPaneSettings property is where you need to define the property pane.
When the properties are defined, you can access them in your web part using this.properties., as shown in the render method in the Knowledge [Bulb in head] window. ${this.properties.description}
Read the Integrating property pane with a web part article to learn more about how to work with the property pane and property pane field types.
http://dev.office.com/sharepoint/docs/spfx/web-parts/basics/integrate-with-property-pane - Replace the propertyPaneSettings methodReplace the propertyPaneSettings method with the code in the Knowledge [Bulb in head] window which shows how to add property types other than TextField.
You can select the code, right-click, click Copy, and then in the code window, right-click and Paste.protected get propertyPaneSettings(): IPropertyPaneSettings {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('description', {
label: 'Description'
}),
PropertyPaneTextField('test', {
label: 'Multi-line Text Field',
multiline: true
}),
PropertyPaneCheckbox('test1', {
text: 'Checkbox'
}),
PropertyPaneDropdown('test2', {
label: 'Dropdown',
options: [
{ key: '1', text: 'One' },
{ key: '2', text: 'Two' },
{ key: '3', text: 'Three' },
{ key: '4', text: 'Four' }
]}),
PropertyPaneToggle('test3', {
label: 'Toggle',
onText: 'On',
offText: 'Off'
})
]
}
]
}
]
};
} - Import property fieldsSince we added new property fields, let's import those from the framework.
Scroll to the top of the file and add the the fields shown in the Knowledge [Bulb in head] window to the import section from @microsoft/sp-client-preview:PropertyPaneCheckbox,
PropertyPaneDropdown,
PropertyPaneToggle - Review the complete import sectionThe complete import section will look like the sample shown in the Knowledge [Bulb in head] window.import {
BaseClientSideWebPart,
IPropertyPaneSettings,
IWebPartContext,
PropertyPaneTextField,
PropertyPaneCheckbox,
PropertyPaneDropdown,
PropertyPaneToggle
} from '@microsoft/sp-client-preview'; - Save the fileSave the file.
- Replace the code in IHelloWorldWebPartProps.tsOpen IHelloWorldWebPartProps.ts and replace the existing code with the code in the Knowledge [Bulb in head] window.
These properties map to our fields we just added.export interface IHelloWorldWebPartProps {
description: string;
test: string;
test1: boolean;
test2: string;
test3: boolean;
}export interface IHelloWorldWebPartProps { description: string; test: string; test1: boolean; test2: string; test3: boolean; }
- Save the fileSave the file.
- Switch back to the HelloWorldWebPart.ts fileSwitch back to the HelloWorldWebPart.ts file.After you add your properties to the web part properties, you can access the property in the same way you accessed the description property earlier:
${this.properties.test2} - Modify HelloWorldWebPart.manifest.json propertiesOpen HelloWorldWebPart.manifest.json and modify the properties to the values shown in the Knowledge [Bulb in head] window.
To set the default value for the property, you will need to update the web part manifest's properties property bag."properties": {
"description": "HelloWorld",
"test": "Multi-line text field",
"test1": true,
"test2": "2",
"test3": true
} - Review the web part manifestThe HelloWorldWebPart.manifest.json file defines the web part metadata such as version, id, display name, icon, and description. Every web part should contain this manifest.{
"$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
"id": "2f1ef3e2-5f37-4da8-b1ff-52c468a28ae2",
"componentType": "WebPart",
"version": "0.0.1",
"manifestVersion": 2,
"preconfiguredEntries": [
{
"groupId": "2f1ef3e2-5f37-4da8-b1ff-52c468a28ae2",
"group": {
"default": "Under Development"
},
"title": {
"default": "HelloWorld"
},
"description": {
"default": "HelloWorld description"
},
"officeFabricIconFontName": "Page",
"properties": {
"description": "HelloWorld",
"test": "Multi-line text field",
"test1": true,
"test2": "2",
"test3": true
}
}
]
}
Exercise 4 : Set up your Office 365 tenant
To build and deploy client-side web parts using the preview release of the SharePoint Framework, you will need an Office 365 tenant and a developer site collection.
Note: The SharePoint Framework is currently in preview and is subject to change. SharePoint Framework client-side web parts are not currently supported for use in production environments.
Note: The SharePoint Framework is currently in preview and is subject to change. SharePoint Framework client-side web parts are not currently supported for use in production environments.
- Sign in to your Office 365 tenantOpen Chrome, and then navigate to http://portal.office.com. Sign in using the Office 365 username and password shown on te Content tab in the lab environment.If you prefer, you can sign in to your own Office 365 E5 or developer tenant.
- Navigate to your SharePoint siteIn Office 365, click SharePoint and record your site URL.
- Create an app catalog siteYou will need an app catalog to upload and deploy web parts. Go to the SharePoint Admin Center by entering the URL https://yourtenantprefix-admin.sharepoint.com in your browser. Replace yourtenantprefix with your Office 365 tenant prefix.
- Select the App CatalogIn the left sidebar, choose the apps menu item and then choose App Catalog.
- Choose OK to create a new app catalog siteChoose OK to create a new app catalog site.
- Enter app catalog detailsIn the next page, enter the details as shown in the Knowledge [Bulb in head] window.
- Title: App Catalog
- Web Site Address suffix: apps
- Administrator: Enter your username and choose the resolve button to resolve the username.
- Choose OK to create the app catalog siteChoose OK to create the app catalog site.SharePoint will create the app catalog site and you will be able to see its progress in the SharePoint admin center.
- Create a new Developer site collectionYou also need a Developer Site.
Go to the SharePoint Admin Center by entering the URL https://yourtenantprefix-admin.sharepoint.com in your browser. Replace yourtenantprefix with your Office 365 Tenant prefix. - Choose New -> Private Site CollectionIn the SharePoint ribbon, choose New -> Private Site Collection.
- Add detailsIn the dialog box, enter the details shown in the Knowledge [Bulb in head] window.
- Title: Developer Site
- Web Site Address suffix: dev
- Template Selection: Select Developer Site as the site collection template.
- Administrator: Enter your username and choose the resolve button to resolve the username.
- Create the site collectionChoose OK to create the site collection.SharePoint will create the developer site and you will be able to see its progress in the SharePoint admin center. After the site is created, you can browse to your developer site collection.
- Set up a document libraryChoose the gears icon on the top right and then choose Site Settings to open the settings page.Make sure you are on your dev site. /Sites/devIn order to use the preview features, you will need to set up a document library with a new column and upload SharePoint workbench. This procedure uses the default document library in your developer site collection. This will be called Documents in the left navigation.
- Choose Site libraries and listsChoose Site libraries and lists under the Site Administration category.
- Choose Customize DocumentsChoose Customize Documents.
- Choose Create columnChoose Create column under Columns.
- Enter ClientSideApplicationId as the column nameEnter ClientSideApplicationId as the column name and leave the other fields at their current values.
- Choose OKChoose OK to create the column.
- Save the SharePoint workbench fileDownload the workbench.aspx file at https://github.com/SharePoint/sp-dev-docs/blob/master/workbench.aspx to your desktop.
Open the context menu (right-click) on the "raw" link in the middle of the page and choose Save Link As to save the file as workbench.aspx to your desktop.You need to upload the SharePoint workbench to test your web parts on SharePoint. - Upload the workbench.aspx fileUpload the file to the Documents library in the dev site collection.If you get the following exception when moving to the workbench.aspx page:
"The requested operation is part of an experimental feature that is not supported in the current environment. The requested operation is part of an experimental feature that is not supported in the current environment."
You are not using a developer tenant. You might be using a first release or normal tenant.
Exercise 5 : Preview the web part in SharePoint
SharePoint workbench is also hosted in SharePoint to preview and test your local web parts in development. The key advantage is that now you are running in SharePoint context and that you will be able to interact with SharePoint data.
- Open SharePoint WorkbenchGo to the following URL: https://your-sharepoint-site/Shared%20Documents/workbench.aspxBy default, your browser is configured not to load scripts from localhost. Workbench will notify you if that is the case.
- Configure the browser to load scripts, if promptedIn order to execute local scripts, you will need to configure the browser to load scripts from unauthenticated sources. This is due to loading scripts over HTTP while connected to a page via HTTPS. Depending on the browser you use, the options to enable this may vary. For example, in the Chrome browser, click the grey shield in the right side of the address bar to load unsafe scripts.In the Chrome browser, click the grey shield in the right side of the address bar to load unsafe scripts.If you used the Chrome browser to load the local workbench, you may not be prompted to load unsafe scripts again.
- Add the hello world web part to the canvasAfter you enable loading scripts, you should see the workbench load. Add the hello world web part to the canvas.Notice that the SharePoint workbench now has the Office 365 Suite navigation bar.
- Reveal the toolboxChoose add icon in the canvas to reveal the toolbox.The toolbox now shows the web parts available on the site where the SharePoint workbench is hosted along with your HelloWorldWebPart.
- Add HelloWorldWebPart from the toolboxAdd HelloWorldWebPart from the toolbox.Now you're running your web part in a page hosted in SharePoint!
Because you are still developing and testing your web part, there is no need to package and deploy your web part to SharePoint.
Congratulations on getting your first Hello World web part running!
No comments:
Post a Comment