Skip to content

Commit 68ba24d

Browse files
authored
fix(templates): update template/plugin and fix import map issue (#12305)
### What? 1. Adds logic to automatically update the `importMap.js` file with the project name provided by the user. 2. Adds an updated version of the `README.md` file that we had when this template existed outside of the monorepo ([here](https://github.com/payloadcms/plugin-template/blob/main/README.md)) to provide clear instructions of required steps. ### Why? 1. The plugin template when installed via `npx create-payload-app` asks the user for a project name, however the exports from `importMap.js` do not get updated to the provided name. This throws errors when running the project and prevents it from building. 2. The `/dev` folder requires the `.env.example` to be copied and renamed to `.env` - the project will not run until this is done. The template lacks instructions that this is a required step. ### How? 1. Updates `packages/create-payload-app/src/lib/configure-plugin-project.ts` to read the `importMap.js` file and replace the placeholder plugin name with the name provided by the users. Adds a test to `packages/create-payload-app/src/lib/create-project.spec.ts` to verify that this file gets updated correctly. 2. Adds instructions on using this template to the `README.md` file, ensuring key steps (like adding the `.env` file) are clearly stated. Additional housekeeping updates: - Removed Jest and replaced it with Vitest for testing - Updated the base test approach to use Vitest instead of Jest - Removed `NextRESTClient` in favor of directly creating Request objects - Abstracted `getCustomEndpointHandler` function - Added ensureIndexes: true to the mongooseAdapter configuration - Removed the custom server from the dev folder - Updated the pnpm dev script to "dev": "next dev dev --turbo" - Removed `admin.autoLogin` Fixes #12198
1 parent 20f7017 commit 68ba24d

File tree

18 files changed

+450
-454
lines changed

18 files changed

+450
-454
lines changed

packages/create-payload-app/src/lib/configure-plugin-project.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,15 @@ export const configurePluginProject = ({
1616
const devPayloadConfigPath = path.resolve(projectDirPath, './dev/payload.config.ts')
1717
const devTsConfigPath = path.resolve(projectDirPath, './dev/tsconfig.json')
1818
const indexTsPath = path.resolve(projectDirPath, './src/index.ts')
19+
const devImportMapPath = path.resolve(projectDirPath, './dev/app/(payload)/admin/importMap.js')
1920

2021
const devPayloadConfig = fse.readFileSync(devPayloadConfigPath, 'utf8')
2122
const devTsConfig = fse.readFileSync(devTsConfigPath, 'utf8')
2223
const indexTs = fse.readFileSync(indexTsPath, 'utf-8')
24+
const devImportMap = fse.readFileSync(devImportMapPath, 'utf-8')
2325

2426
const updatedTsConfig = devTsConfig.replaceAll('plugin-package-name-placeholder', projectName)
27+
const updatedImportMap = devImportMap.replaceAll('plugin-package-name-placeholder', projectName)
2528
let updatedIndexTs = indexTs.replaceAll('plugin-package-name-placeholder', projectName)
2629

2730
const pluginExportVariableName = toCamelCase(projectName)
@@ -43,4 +46,5 @@ export const configurePluginProject = ({
4346
fse.writeFileSync(devPayloadConfigPath, updatedPayloadConfig)
4447
fse.writeFileSync(devTsConfigPath, updatedTsConfig)
4548
fse.writeFileSync(indexTsPath, updatedIndexTs)
49+
fse.writeFileSync(devImportMapPath, updatedImportMap)
4650
}

packages/create-payload-app/src/lib/create-project.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,30 @@ describe('createProject', () => {
6363
expect(packageJson.name).toStrictEqual(projectName)
6464
})
6565

66+
it('updates project name in plugin template importMap file', async () => {
67+
const projectName = 'my-custom-plugin'
68+
const template: ProjectTemplate = {
69+
name: 'plugin',
70+
type: 'plugin',
71+
description: 'Template for creating a Payload plugin',
72+
url: 'https://github.com/payloadcms/payload/templates/plugin',
73+
}
74+
75+
await createProject({
76+
cliArgs: { ...args, '--local-template': 'plugin' } as CliArgs,
77+
packageManager,
78+
projectDir,
79+
projectName,
80+
template,
81+
})
82+
83+
const importMapPath = path.resolve(projectDir, './dev/app/(payload)/admin/importMap.js')
84+
const importMapFile = fse.readFileSync(importMapPath, 'utf-8')
85+
86+
expect(importMapFile).not.toContain('plugin-package-name-placeholder')
87+
expect(importMapFile).toContain('my-custom-plugin')
88+
})
89+
6690
it('creates example', async () => {
6791
const projectName = 'custom-server-example'
6892
const example: ProjectExample = {

templates/plugin/.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,9 @@ yarn-error.log*
4141
.env
4242

4343
/dev/media
44+
45+
# Playwright
46+
/test-results/
47+
/playwright-report/
48+
/blob-report/
49+
/playwright/.cache/

templates/plugin/README.md

Lines changed: 218 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,218 @@
1-
# Plugin
1+
# Payload Plugin Template
2+
3+
A template repo to create a [Payload CMS](https://payloadcms.com) plugin.
4+
5+
Payload is built with a robust infrastructure intended to support Plugins with ease. This provides a simple, modular, and reusable way for developers to extend the core capabilities of Payload.
6+
7+
To build your own Payload plugin, all you need is:
8+
9+
- An understanding of the basic Payload concepts
10+
- And some JavaScript/Typescript experience
11+
12+
## Background
13+
14+
Here is a short recap on how to integrate plugins with Payload, to learn more visit the [plugin overview page](https://payloadcms.com/docs/plugins/overview).
15+
16+
### How to install a plugin
17+
18+
To install any plugin, simply add it to your payload.config() in the Plugin array.
19+
20+
```ts
21+
import myPlugin from 'my-plugin'
22+
23+
export const config = buildConfig({
24+
plugins: [
25+
// You can pass options to the plugin
26+
myPlugin({
27+
enabled: true,
28+
}),
29+
],
30+
})
31+
```
32+
33+
### Initialization
34+
35+
The initialization process goes in the following order:
36+
37+
1. Incoming config is validated
38+
2. **Plugins execute**
39+
3. Default options are integrated
40+
4. Sanitization cleans and validates data
41+
5. Final config gets initialized
42+
43+
## Building the Plugin
44+
45+
When you build a plugin, you are purely building a feature for your project and then abstracting it outside of the project.
46+
47+
### Template Files
48+
49+
In the Payload [plugin template](https://github.com/payloadcms/payload/tree/main/templates/plugin), you will see a common file structure that is used across all plugins:
50+
51+
1. root folder
52+
2. /src folder
53+
3. /dev folder
54+
55+
#### Root
56+
57+
In the root folder, you will see various files that relate to the configuration of the plugin. We set up our environment in a similar manner in Payload core and across other projects, so hopefully these will look familiar:
58+
59+
- **README**.md\* - This contains instructions on how to use the template. When you are ready, update this to contain instructions on how to use your Plugin.
60+
- **package**.json\* - Contains necessary scripts and dependencies. Overwrite the metadata in this file to describe your Plugin.
61+
- .**eslint**.config.js - Eslint configuration for reporting on problematic patterns.
62+
- .**gitignore** - List specific untracked files to omit from Git.
63+
- .**prettierrc**.json - Configuration for Prettier code formatting.
64+
- **tsconfig**.json - Configures the compiler options for TypeScript
65+
- .**swcrc** - Configuration for SWC, a fast compiler that transpiles and bundles TypeScript.
66+
- **vitest**.config.js - Config file for Vitest, defining how tests are run and how modules are resolved
67+
68+
**IMPORTANT\***: You will need to modify these files.
69+
70+
#### Dev
71+
72+
In the dev folder, you’ll find a basic payload project, created with `npx create-payload-app` and the blank template.
73+
74+
**IMPORTANT**: Make a copy of the `.env.example` file and rename it to `.env`. Update the `DATABASE_URI` to match the database you are using and your plugin name. Update `PAYLOAD_SECRET` to a unique string.
75+
**You will not be able to run `pnpm/yarn dev` until you have created this `.env` file.**
76+
77+
`myPlugin` has already been added to the `payload.config()` file in this project.
78+
79+
```ts
80+
plugins: [
81+
myPlugin({
82+
collections: {
83+
posts: true,
84+
},
85+
}),
86+
]
87+
```
88+
89+
Later when you rename the plugin or add additional options, **make sure to update it here**.
90+
91+
You may wish to add collections or expand the test project depending on the purpose of your plugin. Just make sure to keep this dev environment as simplified as possible - users should be able to install your plugin without additional configuration required.
92+
93+
When you’re ready to start development, initiate the project with `pnpm/npm/yarn dev` and pull up [http://localhost:3000](http://localhost:3000) in your browser.
94+
95+
#### Src
96+
97+
Now that we have our environment setup and we have a dev project ready to - it’s time to build the plugin!
98+
99+
**index.ts**
100+
101+
The essence of a Payload plugin is simply to extend the payload config - and that is exactly what we are doing in this file.
102+
103+
```ts
104+
export const myPlugin =
105+
(pluginOptions: MyPluginConfig) =>
106+
(config: Config): Config => {
107+
// do cool stuff with the config here
108+
109+
return config
110+
}
111+
```
112+
113+
First, we receive the existing payload config along with any plugin options.
114+
115+
From here, you can extend the config as you wish.
116+
117+
Finally, you return the config and that is it!
118+
119+
##### Spread Syntax
120+
121+
Spread syntax (or the spread operator) is a feature in JavaScript that uses the dot notation **(...)** to spread elements from arrays, strings, or objects into various contexts.
122+
123+
We are going to use spread syntax to allow us to add data to existing arrays without losing the existing data. It is crucial to spread the existing data correctly – else this can cause adverse behavior and conflicts with Payload config and other plugins.
124+
125+
Let’s say you want to build a plugin that adds a new collection:
126+
127+
```ts
128+
config.collections = [
129+
...(config.collections || []),
130+
// Add additional collections here
131+
]
132+
```
133+
134+
First we spread the `config.collections` to ensure that we don’t lose the existing collections, then you can add any additional collections just as you would in a regular payload config.
135+
136+
This same logic is applied to other properties like admin, hooks, globals:
137+
138+
```ts
139+
config.globals = [
140+
...(config.globals || []),
141+
// Add additional globals here
142+
]
143+
144+
config.hooks = {
145+
...(incomingConfig.hooks || {}),
146+
// Add additional hooks here
147+
}
148+
```
149+
150+
Some properties will be slightly different to extend, for instance the onInit property:
151+
152+
```ts
153+
import { onInitExtension } from './onInitExtension' // example file
154+
155+
config.onInit = async (payload) => {
156+
if (incomingConfig.onInit) await incomingConfig.onInit(payload)
157+
// Add additional onInit code by defining an onInitExtension function
158+
onInitExtension(pluginOptions, payload)
159+
}
160+
```
161+
162+
If you wish to add to the onInit, you must include the **async/await**. We don’t use spread syntax in this case, instead you must await the existing `onInit` before running additional functionality.
163+
164+
In the template, we have stubbed out some addition `onInit` actions that seeds in a document to the `plugin-collection`, you can use this as a base point to add more actions - and if not needed, feel free to delete it.
165+
166+
##### Types.ts
167+
168+
If your plugin has options, you should define and provide types for these options.
169+
170+
```ts
171+
export type MyPluginConfig = {
172+
/**
173+
* List of collections to add a custom field
174+
*/
175+
collections?: Partial<Record<CollectionSlug, true>>
176+
/**
177+
* Disable the plugin
178+
*/
179+
disabled?: boolean
180+
}
181+
```
182+
183+
If possible, include JSDoc comments to describe the options and their types. This allows a developer to see details about the options in their editor.
184+
185+
##### Testing
186+
187+
Having a test suite for your plugin is essential to ensure quality and stability. **Vitest** is a fast, modern testing framework that works seamlessly with Vite and supports TypeScript out of the box.
188+
189+
Vitest organizes tests into test suites and cases, similar to other testing frameworks. We recommend creating individual tests based on the expected behavior of your plugin from start to finish.
190+
191+
Writing tests with Vitest is very straightforward, and you can learn more about how it works in the [Vitest documentation.](https://vitest.dev/)
192+
193+
For this template, we stubbed out `int.spec.ts` in the `dev` folder where you can write your tests.
194+
195+
```ts
196+
describe('Plugin tests', () => {
197+
// Create tests to ensure expected behavior from the plugin
198+
it('some condition that must be met', () => {
199+
// Write your test logic here
200+
expect(...)
201+
})
202+
})
203+
```
204+
205+
## Best practices
206+
207+
With this tutorial and the plugin template, you should have everything you need to start building your own plugin.
208+
In addition to the setup, here are other best practices aim we follow:
209+
210+
- **Providing an enable / disable option:** For a better user experience, provide a way to disable the plugin without uninstalling it. This is especially important if your plugin adds additional webpack aliases, this will allow you to still let the webpack run to prevent errors.
211+
- **Include tests in your GitHub CI workflow**: If you’ve configured tests for your package, integrate them into your workflow to run the tests each time you commit to the plugin repository. Learn more about [how to configure tests into your GitHub CI workflow.](https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs)
212+
- **Publish your finished plugin to NPM**: The best way to share and allow others to use your plugin once it is complete is to publish an NPM package. This process is straightforward and well documented, find out more [creating and publishing a NPM package here.](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages/).
213+
- **Add payload-plugin topic tag**: Apply the tag **payload-plugin **to your GitHub repository. This will boost the visibility of your plugin and ensure it gets listed with [existing payload plugins](https://github.com/topics/payload-plugin).
214+
- **Use [Semantic Versioning](https://semver.org/) (SemVar)** - With the SemVar system you release version numbers that reflect the nature of changes (major, minor, patch). Ensure all major versions reference their Payload compatibility.
215+
216+
# Questions
217+
218+
Please contact [Payload](mailto:[email protected]) with any questions about using this plugin template.

templates/plugin/dev/e2e.spec.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { expect, test } from '@playwright/test'
2+
3+
// this is an example Playwright e2e test
4+
test('should render admin panel logo', async ({ page }) => {
5+
await page.goto('/admin')
6+
7+
// login
8+
await page.fill('#field-email', '[email protected]')
9+
await page.fill('#field-password', 'test')
10+
await page.click('.form-submit button')
11+
12+
// should show dashboard
13+
await expect(page).toHaveTitle(/Dashboard/)
14+
await expect(page.locator('.graphic-icon')).toBeVisible()
15+
})

0 commit comments

Comments
 (0)