Search code examples
rxjsvitenuxt3.js

Nuxt3 - How to use rxjs in development mode


I run a Nuxt3 app which has to use rxjs as a dependency. When running in development mode, rxjs module seems to be imported as CommonJS Module and throws this error:

Cannot find module './internal/Observable'

at Module._resolveFilename (node:internal/modules/cjs/loader:1075:15)
at Module._load (node:internal/modules/cjs/loader:920:27)
at Module.require (node:internal/modules/cjs/loader:1141:19)
at require (node:internal/modules/cjs/helpers:110:18)
at ./rxjs:17:20
at ViteNodeRunner.directRequest (./node_modules/vite-node/dist/client.mjs:331:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async ViteNodeRunner.cachedRequest (./node_modules/vite-node/dist/client.mjs:171:14)
at async ViteNodeRunner.dependencyRequest (./node_modules/vite-node/dist/client.mjs:220:14)
at async ./app.vue:2:31

In production mode, rollup bundling works fine. I've also tested Vite with Vue3 and rxjs and that works as well. So, I guess it is somehow related to the nuxt dev mode??? Any help is greatly appreciated!

For reproduction: https://stackblitz.com/edit/nuxt-starter-vffwrs?file=app.vue


Solution

  • Two things.

    First, Add add a transpile option for rxjs in nuxt config.

    build: {
        transpile: ['rxjs']
    },
    

    Second, subscribe to events in on mounted lifecycle hook. This way you will avoid errors when rendering on the server.

    onMounted(() => {
        fromEvent(document, "click").subscribe(() => console.log("Clicked!"))
    })
    

    This seems to work in the dev mode, haven't checked production mode though.