From 9858e0333418181c68043f2869c49ffe3e077661 Mon Sep 17 00:00:00 2001 From: Eirik Sletteberg Date: Mon, 29 Mar 2021 22:40:02 +0200 Subject: [PATCH] fix(static): serve .js, .jsx, .ts, .tsx as application/javascript This fixes #2642. Thanks a lot to @lukeed, maintainer of Sirv, for the suggestion! https://github.com/lukeed/sirv/pull/103#issuecomment-809633566 --- .../vite/src/node/server/middlewares/static.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/server/middlewares/static.ts b/packages/vite/src/node/server/middlewares/static.ts index 2ccf85e0bced8c..30173bb8b6ea24 100644 --- a/packages/vite/src/node/server/middlewares/static.ts +++ b/packages/vite/src/node/server/middlewares/static.ts @@ -1,12 +1,26 @@ import os from 'os' import path from 'path' -import sirv from 'sirv' +import sirv, { Options } from 'sirv' import { Connect } from 'types/connect' import { ResolvedConfig } from '../..' import { FS_PREFIX } from '../../constants' import { cleanUrl, isImportRequest } from '../../utils' -const sirvOptions = { dev: true, etag: true, extensions: [] } +const sirvOptions: Options = { + dev: true, + etag: true, + extensions: [], + setHeaders(res, pathname) { + // Matches js, jsx, ts, tsx. + // The reason this is done, is that the .ts file extension is reserved + // for the MIME type video/mp2t. In almost all cases, we can expect + // these files to be TypeScript files, and for Vite to serve them with + // this Content-Type. + if (/\.[tj]sx?$/.test(pathname)) { + res.setHeader('Content-Type', 'application/javascript') + } + } +} export function servePublicMiddleware(dir: string): Connect.NextHandleFunction { const serve = sirv(dir, sirvOptions)