frandiox / vite-ssr

Use Vite for server side rendering in Node
MIT License
830 stars 92 forks source link

Module Node Server Export #86

Closed kadiryazici closed 3 years ago

kadiryazici commented 3 years ago

We need a module export option for node applications that runs with mjs.

For example I have a fastify server with module system and I cannot import dist/server/main.js becauase it uses require.

There can be an option like this for module nodejs or vite-ssr can bundle another file as main.mjs

plugins: [
   ssr({
     build: {
        esm: true
     }
   })
]
frandiox commented 3 years ago

This is available in the JS API but not in the CLI/Plugin options. However, maybe it's enough using Vite normal config:

{
  build: {
    rollupOptions: {
      output: {
        format: 'es',
      },
    },
  },
  plugins: [viteSSR(), vue()],
}

Can you check if that works for you? The generated dist/server/package.json will still have type: commonjs though :/

kadiryazici commented 3 years ago

Yes that worked but I had some problems with packages like pinia. It is not importable with module nodejs. So what I did is I wrote a script that renames main.js as main.cjs and after that I was able to use vite-ssr with module nodejs.

frandiox commented 3 years ago

@kadiryazici In the next version, the generated package.json should include type: module or type: commonjs according to the format you provide in the rollup options. I think this should help with imports.

Otherwise, it's also possible to rename the output at will:

viteSSR({
  build: {
    serverOptions: {
      build: {
        rollupOptions: {
          output: {
            dir: undefined,
            file: 'dist/server/main.mjs',
            format: 'es',
          },
        },
      },
    },
})