Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: vite's server.cors not working #104

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 22 additions & 22 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,29 +83,29 @@ export function createSvgIconsPlugin(opt: ViteSvgIconsPlugin): Plugin {
}
},
configureServer: ({ middlewares }) => {
middlewares.use(cors({ origin: '*' }))
middlewares.use(async (req, res, next) => {
const url = normalizePath(req.url!)
const registerId = `/@id/${SVG_ICONS_REGISTER_NAME}`
const clientId = `/@id/${SVG_ICONS_CLIENT}`

const registerId = `/@id/${SVG_ICONS_REGISTER_NAME}`
const clientId = `/@id/${SVG_ICONS_CLIENT}`
if ([clientId, registerId].some((item) => url.endsWith(item))) {
res.setHeader('Content-Type', 'application/javascript')
res.setHeader('Cache-Control', 'no-cache')
const { code, idSet } = await createModuleCode(
cache,
svgoOptions as OptimizeOptions,
options,
)
const content = url.endsWith(registerId) ? code : idSet

res.setHeader('Etag', getEtag(content, { weak: true }))
res.statusCode = 200
res.end(content)
} else {
next()
}
})
middlewares.use(registerId, cors({ origin: '*' }))
middlewares.use(clientId, cors({ origin: '*' }))

const svgIconMiddleware = async (req, res, next) => {
const url = normalizePath(req.url!)
res.setHeader('Content-Type', 'application/javascript')
res.setHeader('Cache-Control', 'no-cache')
const { code, idSet } = await createModuleCode(
cache,
svgoOptions as OptimizeOptions,
options,
)
const content = url.endsWith(registerId) ? code : idSet

res.setHeader('Etag', getEtag(content, { weak: true }))
res.statusCode = 200
res.end(content)
}
middlewares.use(registerId, svgIconMiddleware)
middlewares.use(clientId, svgIconMiddleware)
},
}
}
Expand Down