owlsdepartment / vite-plugin-babel

Runs babel during dev serve in Vite
MIT License
51 stars 14 forks source link

Babel transpilation works perfectly during `dev` / `serve` but not `build` #16

Open jkhaui opened 1 year ago

jkhaui commented 1 year ago

Hey, firstly thanks for the great plugin!

Brief Context

A transitive dependency in my node_modules imports a .png asset using require (i.e. commonjs syntax). Because Vite is basically a plain Node server in SSR phase, and Node doesn't have a native way to parse binary/base64 image data, the app crashes during the SSR pass throwing an "invalid or unexpected token" error.

I should mention that I'm using Astro, but it's basically a light abstraction over Vite and from my debugging I don't think it's causing the issue described below.

Solution (only works during dev/serve)

This is where your plugin saves the day: By using vite-plugin-babel + babel-plugin-transform-assets like below, everything works great now!

vite: {
        plugins: [
            babelPlugin({
                babelConfig: {
                    plugins: [["transform-assets", babelTransformAssetsConfig]]
                }
            })
        ]
    }

Problem

From here I can build the app locally with no errors and also deploy to Vercel where there's similarly no build errors.

But when invoking the SSR page, the app crashes, and inspecting the logs I can see it's because of the "invalid/unexpected token" loading the png. I.e. either vite-plugin-babel, or the babel transform assets plugin, are not running properly during Vite's SSR build phase.

Do you have any insight into this, as the plugin states it should run during all cycles (i.e. optimizeDeps, serve, and build)? Please let me know if there's anything I can do to help provide better observability/logging because I'm not that familiar with Vite's internals. Thanks!

===

A couple more observations which may be relevant:

edit: on second thoughts, this could be caused by astro forcing optimizeDeps.disabled to true during builds. I'll do some further experimenting here

F0rsaken commented 9 months ago

hi! do you have any update on this case? or some repro I can look into?

cyan-2048 commented 4 months ago

here's how I fixed it:


const babelPlugin = babel({
    apply: "build",
    filter: /\.(t|j)sx?$/,
    babelConfig: {
        babelrc: false,
        configFile: false,
        plugins: ["@babel/plugin-transform-parameters"],
    },
});

babelPlugin.enforce = "post";

export default defineConfig({
    plugins: [babelPlugin]
})

works with TypeScript files which is great

cyan-2048 commented 4 months ago

another idea, that filter option might work better if it was a function