A collection of code snippets built with Script Lab.
Note: For all command line interface (CLI) commands mentioned in these instructions, you can use either Git Bash or a Node Command Prompt.
- Fork this project into your GitHub account.
- Clone your fork to your development computer.
- Ensure that you have Node, version 20 or later, installed. (To check the version, run the command
node -v.) - Make sure your CLI is in the root of the office-js-snippets repo and run
npm installto install all dependencies. - Follow the steps in Configuring a remote for a fork to set up the original \OfficeDev\office-js-snippets as the upstream repo for your local repo.
- If you use Visual Studio Code as your editor, install the TSLint extension for Visual Studio Code.
For the git tasks in this procedure, the instructions assume that you're using a CLI. You can use a GUI git client. Consult the client's help to learn how to carry out the same tasks.
-
Create a snippet by using Script Lab. Ensure that the name and description are what you want to be shown publicly. Keep your snippet small. Use standard TypeScript indentation. Improper indentation can cause a failure of the build that you run in a later step. See also the Style guidelines and Size restrictions sections.
-
Select the Share icon, and then choose Copy to Clipboard.
-
Paste the contents into a text editor.
-
Near the top of the file, you see the line
api_set: {}. Change this line to specify the host API version of the most recently added API that your snippet uses. For example, if the snippet is for Excel and it uses some APIs that were introduced in Excel API 1.3, some in 1.4, and some in 1.5, specifyExcelApi 1.5as the value of theapi_setproperty. Put a line break and four spaces before the value and don't include {} characters. To continue the example, when you're done the property looks like this:api_set: ExcelApi: '1.5'
-
Check the name and description property values, also near the top of the file, and edit as needed.
-
Save the file somewhere outside of the office-js-snippets project. (You'll move it into the project in a later step.) The file name must have a ".yaml" extension and it must be in
kebab-case. For examples, see the existing *.yaml files in the subfolders of thesamplesfolder of the project. -
Make sure the main branch of your fork is in sync with the main branch of the upstream \OfficeDev\office-js-snippets repo by following the steps in Syncing a fork.
-
Create a new branch at the office-js-snippets root folder of your local repo by running the command
git checkout -b {name_of_your_new_branch}. (This command creates and checks out the new branch. Stay in this branch for all the remaining steps.) Each snippet should have its own branch. Suggestion: use the name of the yaml file that you created above (without the extension) as the branch name. -
Decide the folder where your snippet should be added. All snippet files must reside within the appropriate subfolder inside the
samplesfolder. Within thesamplesfolder, the structure of subfolders is as follows:- The base folders such as
excel,word, and so on primarily represent the various host applications. - Within each base folder, group folders organize snippets into various categories.
- Within each group folder, each .yaml file represents a snippet.
Note: If your snippet doesn't fit with any existing group folder, create a new group folder inside the base folder. If the existing folders in the base folder begin with numbers, such as
03-range, then your new folder should also begin with a number. Since the numbers determine the sequence of the groups in Script Lab, use a number between the numbers of the groups between which you want the new folder to appear. - The base folders such as
-
Open one of the
.yamlfiles already in the group folder. If it has anorderproperty near the top, then the snippets in the group folder are ordered in a particular sequence in Script Lab. Add anorderproperty to the top of your.yamlfile and give it a number that is between the order numbers of the snippets between which you want it to appear. -
Copy your
.yamlfile to the chosen group folder. -
Run
npm start. If there are no problems, the output ends with aDone!. If there are errors, review the output to check what caused the build validation to fail, and fix as needed. See Known errors and fixes for more information.Note: The
npm startcommand adds anidproperty to the top of the file. -
Re-run
npm start, and fix errors, until the build succeeds. -
Run
npm testto validate your snippet compiles correctly and all library URLs are reachable. This command runs the same tests that run automatically in CI when you create your pull request. If there are errors, fix them and re-run the tests.Note: You can also run
npm run validateto run the full validation suite (build + lint + tests) in one command. -
Run
git status. You should see that, in addition to your new.yamlfile (or possibly new folder), aplaylist\{host}.yamlfile (where{host}isexcel,word, and so on) is also changed. This change is expected. The build tool you just ran added a reference to your new snippet to this file. -
Run the following two commands. The commit message should be a brief description of what the snippet demonstrates; for example,
"shows how to use getWhatever method".git add -A git commit -m "{commit message}" -
Push the snippet to your fork by running:
git push --set-upstream origin {name_of_your_new_branch} -
Now you create a pull request. In your fork on GitHub, switch to your new branch.
-
Choose New pull request.
-
On the Open a pull request page, verify that:
- the base fork is
OfficeDev/office-js-snippets - the base branch is
main - the head fork is
{your-GitHub-account}/office-js-snippets - the "compare" branch is
{name_of_your_new_branch}.
- the base fork is
-
The title of the pull request defaults to your commit message. Change it as needed and optionally add a comment to provide additional information about the pull request to the reviewers.
-
At least one reviewer must approve all pull requests to office-js-snippets. On the right side of the page is a Reviewers section. You can optionally suggest one or more people to review the pull request. (GitHub sometimes lists one or more admins of the repo by default, but it isn't consistent in doing this.) Your pull request is reviewed even if you don't suggest anyone.
-
Choose Create pull request The page for your pull request opens. There is initially a message on the page saying Some checks haven't completed yet. The CI system automatically validates your snippet by running build, lint, and test checks. It usually takes a few minutes.
Note: Since your pull request passed locally (both
npm startandnpm test), it should pass the CI checks too. The CI validates TypeScript compilation, library URLs, and code quality. If CI fails, check the error messages and fix the issues locally, then push your changes to update the pull request. -
The reviewers might make comments on your pull request and ask you to make changes. Make changes in Script Lab and then repeat the process of creating the
.yamlfile. You don't have to create the new branch again, but make sure it is checked out when you copy the changed.yamlfile over the previous version. After you commit and push the changed version to your fork, the new version is automatically added to your existing pull request. Do not create a new pull request. -
When the reviewers are satisfied, your pull request is merged to the
mainbranch and the pull request is closed.Note: In a few days, the repo admins merge your snippet into the
prodbranch. It then appears in the Samples area of Script Lab. (It's in the My Snippets area as soon as you create it.) -
Optionally, you can delete the branch you created from your fork and/or your local clone.
- An error that says the
nameproperty has uppercase letters or other disallowed characters doesn't refer to thenameproperty in the file. It refers to the file name itself. You also get this error if the file extension isn't.yaml.
The basic snippet structure is as follows:
$("#run").on("click", () => tryCatch(run));
async function run() {
await Word.run(async (context) => {
const range = context.document.getSelection();
range.font.color = "blue";
await context.sync();
});
}
/** Default helper for invoking an action and handling errors. */
async function tryCatch(callback) {
try {
await callback();
}
catch (error) {
OfficeHelpers.UI.notify(error);
OfficeHelpers.Utilities.log(error);
}
}A few style rules to observe:
- Use standard TypeScript indentation.
- For each button, define a corresponding
asyncfunction to run when the button is clicked. If the page has only one button, you can name theasyncfunctionrun. Otherwise, choose a descriptive name. - Each button-click handler should call the
tryCatchfunction, passing in the name of theasyncfunction to execute when the button is clicked. - Use
all-lower-case-and-hyphenatedfor all HTML IDs. - Unless you're explicitly showing a polished UI, you don't need to include the popup notification except for one or two samples. It's a lot of HTML and JavaScript code, and it's not strictly Fabric-y. There's a more "correct" way to do this by using components.
- Use double quotes for strings.
- Don't forget the semicolons.
Librariesin snippets must have a specific version. For example, usejquery@3.1.1.
Script Lab is designed for you to play with small code samples. Generally, a snippet should be at most a few hundred lines and a few thousand characters.
Your snippet can use hard-coded data. A small amount of data (say, a few hundred characters) is okay to hard code in Script Lab. However, for larger pieces of data, store those externally and then load them at runtime by using a command like fetch.
Keep your snippets and hard-coded data small. Storing several large snippets can exceed Script Lab's storage and cause problems when loading Script Lab.
- The scripts for building and validating the snippets are under the
configfolder. In particular, they're underbuild.ts.
Note: If you debug in Visual Studio Code, you can use "F5" to attach the debugger. However, be sure to run
npm run tscbefore you do (and after any code change!).F5isn't set to recompile.
Join the Microsoft 365 Developer Program to get resources and information to help you build solutions for the Microsoft 365 platform, including recommendations tailored to your areas of interest.
You might also qualify for a free developer subscription that's renewable for 90 days and comes configured with sample data. For details, see the FAQ.
This project adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
