Reputation: 968
I installed an npm package, but since we can't use imports in nuxt 3, I don't get how to use it and couldn't find anything about this in the documentation. Does anyone know how to deal with this?
Upvotes: 2
Views: 4600
Reputation: 4623
What kind of library you want to add to the project? Nuxt reads all files in your project and will import your imports inside of them. You need just pay attention, are library is made to be used in node.js or client browser. Exception to that are Nuxt modules you need to include in modules array inside nuxt.config
files, but the intention of that is you won't need to import them in your project files for example.
Using the composable setup function, in the reality it is a simple async function
that will run on a server and SSR HTML for client, so every thing you do directly there need to be safe to use in node.js.
Unless:
<ClientOnly>
component. Component won't be rendered on server.onMounted(() => {...})
.if(process.client) {...}
.Here is an example of plugin that runs on server and client.
import { defineNuxtPlugin } from '#app'
// Those imports are streight from node_modules installed
// using yarn add -D firebase or npm install -D firebase
// -D stands for devDependencies in package.json.
// You no need to install enything in "dependencies"
import { initializeApp, getApps } from '@firebase/app'
import { getAuth, onAuthStateChanged } from '@firebase/auth'
export default defineNuxtPlugin((nuxtApp) => {
const firebaseConfig = { ...useRuntimeConfig().public.firebaseConfig }
if (!getApps().length) initializeApp(firebaseConfig)
if(process.client) {
onAuthStateChanged(getAuth(), user => {
const currentUser = useState('user')
currentUser.value = user
})
}
}
Firebase is initialized on a server to be able to fetch data and SSR HTML files to a client. Then on client Firebase is initialized and it triggers onAuthStateChanges()
function. This function initiate WebSocket connection with authentication system. It's in if(proces.client)
so it won't trigger in node.js.
Upvotes: 3