vitejs / vite

Next generation frontend tooling. It's fast!
http://vite.dev
MIT License
68.43k stars 6.17k forks source link

Allow preview mode for libraries #7009

Open yarinsa opened 2 years ago

yarinsa commented 2 years ago

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:

  1. Developer run yarn vite preview
  2. 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

chardin1 commented 2 years ago

@Niputi What's the status on this?

vilbergs commented 1 year ago

Upvoting this. It would be great if this was possible so that we can more easily run our e2e tests on the production bundle.

ursnj commented 1 year ago

This is definitly needed

mattsouth commented 1 year ago

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.

RomainSF commented 1 year ago

+1, I need to run transformIndexHtml during preview only

morganney commented 8 months ago

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.

ultimateshadsform commented 6 months ago

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:

image