Skip to content

Commit

Permalink
docs: integration with next.config.js in ESM mode
Browse files Browse the repository at this point in the history
ref: #37
  • Loading branch information
zce committed Feb 6, 2024
1 parent f046bbe commit 9407e42
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
38 changes: 37 additions & 1 deletion docs/guide/with-nextjs.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ You can use the Next.js plugin to call Velite's programmatic API to start Velite

in your `next.config.js`:

```js
::: code-group

```js [CommonJS]
/** @type {import('next').NextConfig} */
module.exports = {
// othor next config here...
Expand Down Expand Up @@ -41,6 +43,40 @@ class VeliteWebpackPlugin {
}
```
```js [ESM]
import { build } from 'velite'

/** @type {import('next').NextConfig} */
export default {
// othor next config here...
webpack: config => {
config.plugins.push(new VeliteWebpackPlugin())
return config
}
}

class VeliteWebpackPlugin {
static started = false
constructor(/** @type {import('velite').Options} */ options = {}) {
this.options = options
}
apply(/** @type {import('webpack').Compiler} */ compiler) {
// executed three times in nextjs !!!
// twice for the server (nodejs / edge runtime) and once for the client
compiler.hooks.beforeCompile.tap('VeliteWebpackPlugin', async () => {
if (VeliteWebpackPlugin.started) return
VeliteWebpackPlugin.started = true
const dev = compiler.options.mode === 'development'
this.options.watch = this.options.watch ?? dev
this.options.clean = this.options.clean ?? !dev
await build(this.options) // start velite
})
}
}
```
:::
::: tip
The Next.js plugin is still under development...
Expand Down
29 changes: 29 additions & 0 deletions examples/nextjs/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,35 @@ class VeliteWebpackPlugin {
}
```

or ESM version (package.json with `"type": "module"`):

```js
import { build } from 'velite'

/** @type {import('next').NextConfig} */
export default {
// othor next config here...
webpack: config => {
config.plugins.push(new VeliteWebpackPlugin())
return config
}
}

class VeliteWebpackPlugin {
static started = false
apply(/** @type {import('webpack').Compiler} */ compiler) {
// executed three times in nextjs
// twice for the server (nodejs / edge runtime) and once for the client
compiler.hooks.beforeCompile.tap('VeliteWebpackPlugin', async () => {
if (VeliteWebpackPlugin.started) return
VeliteWebpackPlugin.started = true
const dev = compiler.options.mode === 'development'
await build({ watch: dev, clean: !dev })
})
}
}
```

#### MDX Bundle

```typescript
Expand Down

0 comments on commit 9407e42

Please sign in to comment.