diff --git a/README.md b/README.md index b33950c..1ae2e17 100644 --- a/README.md +++ b/README.md @@ -319,6 +319,50 @@ fastify.register('@fastify/swagger-ui', { Note that this behavior is disabled by default in `@fastify/swagger-ui`. +### Bundling + +To bundle Swagger UI with your application, the swagger-ui static files need to be copied to the server and the `baseDir` option set to point to the file directory. +
+Copy files with esbuild + +```js +import { build } from 'esbuild' +import { copy } from 'esbuild-plugin-copy' + +await build({ + // ... + plugins: [ + copy({ + resolveFrom: 'cwd', + assets: { + from: ['node_modules/@fastify/swagger-ui/static/*'], + to: ['dist/static'], + }, + }), + ], +}) +``` + +
+ +
+Copy files with docker + +```Dockerfile +COPY ./node_modules/@fastify/swagger-ui/static /app/static +``` + +
+ +#### Configure Swagger UI to use a custom baseDir +Set the `baseDir` option to point to your folder. + +```js +await fastify.register(require('@fastify/swagger-ui'), { + baseDir: isDev ? undefined : path.resolve('static'), +}) +``` + ## License diff --git a/lib/routes.js b/lib/routes.js index 3e5ae45..e8ca8ce 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -202,7 +202,7 @@ function fastifySwagger (fastify, opts, done) { // serve swagger-ui with the help of @fastify/static fastify.register(fastifyStatic, { - root: path.join(__dirname, '..', 'static'), + root: opts.baseDir || path.join(__dirname, '..', 'static'), prefix: staticPrefix, decorateReply: false }) diff --git a/test/route.test.js b/test/route.test.js index 08e9051..a55c19a 100644 --- a/test/route.test.js +++ b/test/route.test.js @@ -373,6 +373,33 @@ test('/documentation/static/:file should send back the correct file', async (t) } }) +test('/documentation/static/:file should send back file from baseDir', async (t) => { + t.plan(2) + const fastify = Fastify() + + const uiConfig = { + baseDir: resolve(__dirname, '..', 'examples', 'static') + } + + await fastify.register(fastifySwagger, swaggerOption) + await fastify.register(fastifySwaggerUi, uiConfig) + + { + const res = await fastify.inject({ + method: 'GET', + url: '/documentation/static/example-logo.svg' + }) + t.equal(res.statusCode, 200) + t.equal( + res.payload, + readFileSync( + resolve(__dirname, '..', 'examples', 'static', 'example-logo.svg'), + 'utf8' + ) + ) + } +}) + test('/documentation/static/:file 404', async (t) => { t.plan(2) const fastify = Fastify()