vitejs / vite

Next generation frontend tooling. It's fast!
http://vitejs.dev
MIT License
67.16k stars 6.04k forks source link

[Feature Request] Add resolve options to worker and ssr configurations #13780

Open haikyuu opened 1 year ago

haikyuu commented 1 year ago

Description

It is sometimes very useful to differentiate between resolution in different contexts (server, browser, worker and why not tests)

An example is a shared library that should work in node, client and workers but with some differences. A common thing is to put the differing parts in separate files for each platform.

Suggested solution

import core from './core'
# resolves based on environment and config
# core.server.js
# core.browser.js
# core.worker.js

With the following configuration

export default {
  resolve: { extensions: ['.browser.js', '.js'] },
  ssr: { resolve: { extensions: ['.server.js', '.js'] } },
  worker: { resolve: { extensions: ['.worker.js', '.js'] } },
  // test: { resolve: { extensions: ['.vitest.js', '.js'] } },
}

Alternative

The alternative would be to explicitely check for the current environment and use dynamic imports which is quite a gymnastic.

Additional context

A part of this pattern (Platform-specific extensions) is quite common and useful in react-native https://reactnative.dev/docs/platform-specific-code#platform-specific-extensions

Validations

bluwy commented 1 year ago

Related: https://github.com/vitejs/vite/pull/13487#issuecomment-1592846430