vite
vite copied to clipboard
Allow preview mode for libraries
Clear and concise description of the problem
I am building a web SDK.
I used the lib mode to configure my outputs.
I am developing the library in esm
and my library is gonna be served in cjs
. In order to make sure it's working (tests and manually) I need to copy/create index.html file and reference the output script (vite does it on regular mode OOO).
Suggested solution
Therefore I want to allow 'lib preview' let me explain:
- Developer run
yarn vite preview
- Preview server is starting (same as today), but it copies the HTML file to the dist and do the following (this piece of code I wrote in a vite plugin)
transformIndexHtml: async (htmlString) => {
const htmlStringWithScript = htmlString.replace(
`<script type="module" src="./src/index.ts"></script>`,
`<script src="sdk.cjs.js"></script>`,
);
return htmlStringWithScript;
},
Alternative
Allow configuring 'preview' options to serve libraries
Additional context
I am also willing to contribute and open PR, if the authors will see this feature as meaningful to the platform
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guidelines.
- [X] Read the docs.
- [X] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
@Niputi What's the status on this?
Upvoting this. It would be great if this was possible so that we can more easily run our e2e tests on the production bundle.
This is definitly needed
A workaround Ive used is a second config file, i.e. vite.preview.js that's based on the default but doesnt have the library config. Then change your packages.json preview script to be vite build -c vite.preview.js && vite preview
.
+1, I need to run transformIndexHtml during preview only
This produces a build of the index.html
file used to demo my lib in the output directory:
rollupOptions: {
input: {
'index.html': 'index.html',
},
},
allowing me to npm run build
and then npm run preview
.
If you don't want the demo index.html
file in your published build use an env var to adjust the config.
My solution was to create 2 vite.ts config files. Default vite config ts is in lib mode using lib things and the second one without that has all the normal website stuff.
First one configured as lib and the other one as normal and then in my package json:
"scripts": {
"dev": "vite --config vite-website.config.ts",
"build": "bun run build:lib && bun run build:web",
"build:lib": "vue-tsc && vite build",
"build:web": "vue-tsc && vite build --config vite-website.config.ts",
"preview": "vite preview --config vite-website.config.ts"
},
Output is in two folders: