Skip to content

Commit

Permalink
feat: add React Router 7 plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
mrstork authored and serhalp committed Dec 10, 2024
1 parent e680b93 commit 95339a7
Show file tree
Hide file tree
Showing 46 changed files with 1,635 additions and 249 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,6 @@ build/

# Generated by `deno types`
/packages/remix-edge-adapter/deno.d.ts

# React Router
.react-router/
7 changes: 6 additions & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
{"packages/remix-edge-adapter":"3.4.2","packages/remix-runtime":"2.3.1","packages/remix-adapter":"2.5.1"}
{
"packages/remix-edge-adapter": "3.4.2",
"packages/remix-runtime": "2.3.1",
"packages/remix-adapter": "2.5.1",
"packages/vite-plugin-react-router": "0.0.0"
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"p-limit": "^5.0.0",
"prettier": "^3.0.0",
"typescript": "^5.0.0",
"vitest": "^1.0.0"
"vitest": "^2.1.8"
},
"dependencies": {
"@netlify/edge-functions": "^2.10.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/remix-adapter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tsup": "^8.0.2",
"vite": "^5.1.3"
"vite": "^5.4.11"
},
"peerDependencies": {
"vite": "^5.0.0"
Expand Down
1 change: 1 addition & 0 deletions packages/vite-plugin-react-router/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Changelog
16 changes: 16 additions & 0 deletions packages/vite-plugin-react-router/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
MIT License

Copyright (c) Netlify Inc. 2024

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 changes: 29 additions & 0 deletions packages/vite-plugin-react-router/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# React Router Adapter for Netlify

The React Router Adapter for Netlify allows you to deploy your [React Router](https://reactrouter.com) app to
[Netlify Functions](https://docs.netlify.com/functions/overview/).

To deploy a React Router 7+ site to Netlify, install this package:

## How to use

```sh
npm install @netlify/vite-plugin-react-router
```

and include the Netlify plugin in your `vite.config.ts`:

```typescript
import { reactRouter } from '@react-router/dev/vite'
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
import netlifyPlugin from '@netlify/vite-plugin-react-router' // <- add this
export default defineConfig({
plugins: [
reactRouter(),
tsconfigPaths(),
netlifyPlugin(), // <- add this
],
})
```
70 changes: 70 additions & 0 deletions packages/vite-plugin-react-router/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"name": "@netlify/vite-plugin-react-router",
"version": "0.0.0",
"description": "React Router 7+ Vite plugin for Netlify",
"type": "commonjs",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
}
},
"files": [
"dist/**/*",
"LICENSE",
"README.md",
"CHANGELOG.md"
],
"scripts": {
"prepack": "pnpm run build",
"build": "tsup-node src/index.ts --format esm,cjs --dts --target node18 --clean",
"build:watch": "pnpm run build --watch"
},
"repository": {
"type": "git",
"url": "https://github.com/netlify/remix-compute",
"directory": "packages/vite-plugin-react-router"
},
"keywords": [
"react-router",
"vite-plugin",
"netlify"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/netlify/remix-compute/issues"
},
"homepage": "https://github.com/netlify/remix-compute#readme",
"dependencies": {
"@react-router/node": "^7.0.1",
"isbot": "^5.0.0",
"react-router": "^7.0.1"
},
"devDependencies": {
"@netlify/functions": "^2.8.1",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tsup": "^8.0.2",
"vite": "^5.4.11"
},
"peerDependencies": {
"vite": ">=5.0.0"
},
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public"
}
}
4 changes: 4 additions & 0 deletions packages/vite-plugin-react-router/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type { GetLoadContextFunction, RequestHandler } from './server'
export { createRequestHandler } from './server'

export { netlifyPlugin as default } from './plugin'
106 changes: 106 additions & 0 deletions packages/vite-plugin-react-router/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import type { Plugin, ResolvedConfig } from 'vite'
import { mkdir, writeFile } from 'node:fs/promises'
import { join, relative, sep } from 'node:path'
import { sep as posixSep } from 'node:path/posix'
import { version, name } from '../package.json'

const NETLIFY_FUNCTIONS_DIR = '.netlify/functions-internal'

const FUNCTION_FILENAME = 'react-router-server.mjs'
/**
* The chunk filename without an extension, i.e. in the Rollup config `input` format
*/
const FUNCTION_HANDLER_CHUNK = 'server'

const FUNCTION_HANDLER_MODULE_ID = 'virtual:netlify-server'
const RESOLVED_FUNCTION_HANDLER_MODULE_ID = `\0${FUNCTION_HANDLER_MODULE_ID}`

const toPosixPath = (path: string) => path.split(sep).join(posixSep)

// The virtual module that is the compiled Vite SSR entrypoint (a Netlify Function handler)
const FUNCTION_HANDLER = /* js */ `
import { createRequestHandler } from "@netlify/vite-plugin-react-router";
import * as build from "virtual:react-router/server-build";
export default createRequestHandler({
build,
getLoadContext: async (_req, ctx) => ctx,
});
`

// This is written to the functions directory. It just re-exports
// the compiled entrypoint, along with Netlify function config.
function generateNetlifyFunction(handlerPath: string) {
return /* js */ `
export { default } from "${handlerPath}";
export const config = {
name: "React Router server handler",
generator: "${name}@${version}",
path: "/*",
preferStatic: true,
};
`
}

export function netlifyPlugin(): Plugin {
let resolvedConfig: ResolvedConfig
let currentCommand: string
let isSsr: boolean | undefined
return {
name: 'vite-plugin-react-router-netlify-functions',
config(config, { command, isSsrBuild }) {
currentCommand = command
isSsr = isSsrBuild
if (command === 'build') {
if (isSsrBuild) {
// We need to add an extra SSR entrypoint, as we need to compile
// the server entrypoint too. This is because it uses virtual
// modules.
// NOTE: the below is making various assumptions about the React Router Vite plugin's
// implementation details:
// https://github.com/remix-run/remix/blob/cc65962b1a96d1e134336aa9620ef1dad7c5efb1/packages/remix-dev/vite/plugin.ts#L1149-L1168
// TODO(serhalp) Stop making these assumptions or assert them explictly.
// TODO(serhalp) Unless I'm misunderstanding something, we should only need to *replace*
// the default React Router Vite SSR entrypoint, not add an additional one.
if (typeof config.build?.rollupOptions?.input === 'string') {
config.build.rollupOptions.input = {
[FUNCTION_HANDLER_CHUNK]: FUNCTION_HANDLER_MODULE_ID,
index: config.build.rollupOptions.input,
}
if (config.build.rollupOptions.output && !Array.isArray(config.build.rollupOptions.output)) {
config.build.rollupOptions.output.entryFileNames = '[name].js'
}
}
}
}
},
async resolveId(source) {
if (source === FUNCTION_HANDLER_MODULE_ID) {
return RESOLVED_FUNCTION_HANDLER_MODULE_ID
}
},
// See https://vitejs.dev/guide/api-plugin#virtual-modules-convention.
load(id) {
if (id === RESOLVED_FUNCTION_HANDLER_MODULE_ID) {
return FUNCTION_HANDLER
}
},
async configResolved(config) {
resolvedConfig = config
},
// See https://rollupjs.org/plugin-development/#writebundle.
async writeBundle() {
// Write the server entrypoint to the Netlify functions directory
if (currentCommand === 'build' && isSsr) {
const functionsDirectory = join(resolvedConfig.root, NETLIFY_FUNCTIONS_DIR)

await mkdir(functionsDirectory, { recursive: true })

const handlerPath = join(resolvedConfig.build.outDir, `${FUNCTION_HANDLER_CHUNK}.js`)
const relativeHandlerPath = toPosixPath(relative(functionsDirectory, handlerPath))

await writeFile(join(functionsDirectory, FUNCTION_FILENAME), generateNetlifyFunction(relativeHandlerPath))
}
},
}
}
53 changes: 53 additions & 0 deletions packages/vite-plugin-react-router/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { AppLoadContext, ServerBuild } from 'react-router'
import { createRequestHandler as createReactRouterRequestHandler } from 'react-router'
import type { Context as NetlifyContext } from '@netlify/functions'

type LoadContext = AppLoadContext & NetlifyContext

/**
* A function that returns the value to use as `context` in route `loader` and
* `action` functions.
*
* You can think of this as an escape hatch that allows you to pass
* environment/platform-specific values through to your loader/action.
*/
export type GetLoadContextFunction = (request: Request, context: NetlifyContext) => Promise<LoadContext> | LoadContext

export type RequestHandler = (request: Request, context: LoadContext) => Promise<Response | void>

/**
* Given a build and a callback to get the base loader context, this returns
* a Netlify Function handler (https://docs.netlify.com/functions/overview/) which renders the
* requested path. The loader context in this lifecycle will contain the Netlify Functions context
* fields merged in.
*/
export function createRequestHandler({
build,
mode,
getLoadContext,
}: {
build: ServerBuild
mode?: string
getLoadContext?: GetLoadContextFunction
}): RequestHandler {
const reactRouterHandler = createReactRouterRequestHandler(build, mode)

return async (request: Request, netlifyContext: NetlifyContext): Promise<Response | void> => {
const start = Date.now()
console.log(`[${request.method}] ${request.url}`)
try {
const mergedLoadContext = (await getLoadContext?.(request, netlifyContext)) || netlifyContext

const response = await reactRouterHandler(request, mergedLoadContext)

// A useful header for debugging
response.headers.set('x-nf-runtime', 'Node')
console.log(`[${response.status}] ${request.url} (${Date.now() - start}ms)`)
return response
} catch (error) {
console.error(error)

return new Response('Internal Error', { status: 500 })
}
}
}
9 changes: 9 additions & 0 deletions packages/vite-plugin-react-router/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"jsx": "react-jsx",
"outDir": "./build"
},
"include": ["./src"]
}
12 changes: 12 additions & 0 deletions packages/vite-plugin-react-router/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/// <reference types="vitest" />
/// <reference types="vite/client" />

import { defineProject } from 'vitest/config'

export default defineProject({
plugins: [],
test: {
include: ['./__tests__/*.{js,jsx,tsx,ts}'],
globals: true,
},
})
Loading

0 comments on commit 95339a7

Please sign in to comment.