Giter VIP home page Giter VIP logo

framework's Introduction

๐Ÿšง Repository update ๐Ÿšง

The repository for Nuxt 3 has updated to be https://github.com/nuxt/nuxt - please raise new issues, discussions and pull requests there ๐Ÿ™

For progress you can follow #10147, and you can read more about our plans in the Nuxt 2023 vision.


Nuxt banner

๐Ÿ‘‹ Welcome to Nuxt

Nuxt's goal is to make web development intuitive and performant, with a great developer experience.
Learn more in the 'What is Nuxt?' section of our documentation.

Version Downloads License Volta board


Documentation

We highly recommend you take a look at the Nuxt documentation to level up.


Modules

Discover our list of modules to supercharge your Nuxt project. Created by the Nuxt team and community.


Examples

Explore different ways of using Nuxt features and get inspired with our list of examples.


Reporting bugs

Check out the Reporting Bugs page.


Suggestions

Check out the Contribution page.


Questions

Check out the Getting Help page.

Local Development

Follow the docs to Set Up Your Local Development Environment to contribute to the framework and documentation.

Follow us

Discordย ย Twitterย ย GitHub

License

MIT

framework's People

Contributors

516310460 avatar antfu avatar ascorbic avatar atinux avatar carolinadelerue avatar cawa-93 avatar clarkdo avatar clemcode avatar damianglowala avatar danielroe avatar diizzayy avatar farnabaz avatar flosciante avatar harlan-zw avatar hecktarzuli avatar huang-julien avatar huynl-96 avatar jamesgeorge007 avatar kazupon avatar kevinmarrec avatar krutie avatar mannil avatar mini-ghost avatar pi0 avatar renovate[bot] avatar smarroufin avatar tobiasdiez avatar valcosmos avatar vencho-mdp avatar webfansplz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

framework's Issues

Fail load JS after build

Environment

  • Operating System: Darwin
  • Node Version: v16.13.0
  • Nuxt Version: 3.0.0-27447229.20f3171
  • Package Manager: [email protected]
  • Bundler: Vite
  • User Config: ssr, nitro, meta
  • Runtime Modules: -
  • Build Modules: -

Reproduction

https://github.com/kantin13/failLoadJsAfterBuild

Describe the bug

Hello,
I am migrating my project to Nuxt V3 and I have an error that I cannot solve. I want to import a js file in the head and call a function when the page is loaded. Any function when I am in npm run dev but when I build my function is not recognized anymore, any idea?

image

image

and after build :
image

Additional context

No response

Logs

No response

Passing configuration to serverMiddleware in nuxt2-bridge no more possible

Environment

------------------------------
- Operating System: `Linux`
- Node Version:     `v16.13.1`
- Nuxt Version:     `2.16.0-27292334.ab1c6cb4`
- Package Manager:  `[email protected]`
- Bundler:          `Webpack`
- User Config:      `head`, `css`, `plugins`, `components`, `buildModules`, `modules`, `build`, `bridge`, `typescript`, `graphqlMiddleware`, `publicRuntimeConfig`, `privateRuntimeConfig`
- Runtime Modules:  `~/modules/nuxt-graphql-middleware/src/module.ts`
- Build Modules:     `@nuxt/[email protected]`

Reproduction

In Nuxt 2 we added a serverMiddleware from the module like that:

  // Add the server middleware.
  this.addServerMiddleware({
    path: config.endpointNamespace,
    handler: serverMiddleware(
      config.graphqlServer,
      queries,
      mutations,
      config.server
    ),
  })

We need to pass a lot of configuration to the middleware defined in nuxt.config.ts.

Describe the bug

With Nuxt2 bridge we cannot pass a function anymore. It does not work with nitro if we pass a function. We have to pass a file path to build the standalone nitro server.

But how can we pass all the configuration settings?

There must be a way to access the nuxt configuration some how?

// middleware.ts
import { createApp } from 'h3'

const app = createApp()
app.use('/hello', () => {
  return {
    hello: 'world',
  }
})
export default app
// module.ts
  const MIDDLEWARE_PATH = path.resolve(__dirname, 'middleware.ts')

  this.addServerMiddleware({
    path: config.endpointNamespace,
    handler: MIDDLEWARE_PATH
  })

How can we somehow pass the configuration?

Additional context

No response

Logs

No response

`NuxtLink` component

Nuxt 2 has a build-in NuxtLink that is basically a wrapper over <RouterLink> with some improvements like page smart prefetching. We shall support t for Nuxt 3 as a built-in app component:

  • Wrapping RouterLink when pages/ directory enabled
  • Handling external links with default noopener and bypassing RouterLink
  • (in the future) Add back prefetch
  • (in the future) Ability to seemless switch between different SPA builds

Some more ideas to discover by @lihbr: https://lihbr.com/blog/one-link-component-to-rule-them-all

Generate routes unexpected indentifier

Environment


  • Operating System: Darwin
  • Node Version: v16.14.2
  • Nuxt Version: 3.0.0-27506609.eed7036
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

import { defineNuxtConfig } from "nuxt3";
import { $fetch } from "ohmyfetch";

const dynamicRoutes = async (): Promise<string[]> => {
  return $fetch<
    {
      userId: number;
      id: number;
      title: string;
      complted: boolean;
    }[]
  >("https://jsonplaceholder.typicode.com/todos").then((data) => {
    return data.map((x) => `/${x.title.replace(/\s/g, "-")}`);
  });
};

// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
  typescript: {
    strict: true,
  },
  target: "static",
  generate: {
    routes: await dynamicRoutes(),
  },
});

Describe the bug

After reading the documentatie of the generate routes function i tried to implement this see code example but when ran i get the following error :

 ERROR  Unexpected identifier                                                                                                                                                   08:01:35

  routes: await dynamicRoutes() } });exports.default = _default;
  ^^^^^^^^^^^^^
  
  SyntaxError: Unexpected identifier
  at new Script (node:vm:100:7)
  at createScript (node:vm:257:10)
  at Object.runInThisContext (node:vm:305:10)
  at jiti (node_modules/jiti/dist/jiti.js:1:196321)
  at resolveConfig (node_modules/c12/dist/index.mjs:179:18)
  at loadConfig (node_modules/c12/dist/index.mjs:97:40)
  at async loadNuxtConfig (node_modules/@nuxt/kit/dist/index.mjs:625:59)
  at async loadNuxt (node_modules/nuxt3/dist/index.mjs:1362:19)
  at async loadNuxt (node_modules/@nuxt/kit/dist/index.mjs:657:19)
  at async Object.invoke (node_modules/nuxi/dist/chunks/build.mjs:28:18)

when package install from `github`, can't `build`

Environment

Nuxt project info: 14:10:19


  • Operating System: Darwin
  • Node Version: v16.13.0
  • Nuxt Version: 3.0.0-rc.0-27508091.78fcbcf
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: alias, target
  • Runtime Modules: -
  • Build Modules: -

Reproduction

https://codesandbox.io/s/b4cvt4?file=/package.json:134-142

Describe the bug

when use ssh way install package,like:

"dependencies": {
    "is-https": "github:unjs/is-https",
  }

can not build, i test with vite, vite is ok, but nuxt3 is not

Additional context

No response

Logs

No response

Volar not working with Nuxt 3

Environment


  • Operating System: Darwin
  • Node Version: v14.17.0
  • Nuxt Version: 3-3.0.0-27234368.47ea41d
  • Package Manager: npm
  • Bundler: Webpack
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Describe the bug and expected behavior

The docs have 3 downloads in the recommended downloads section and one of them is Volar.
After uninstalling Vetur and installing Volar, all emmet snippets just disappeared.

Steps to reproduce

  1. Uninstall Vetur
  2. Install Volar
  3. Use emmet on a fresh Nuxt3 installation

Additional context

The Volar GitHub repo is pretty inactive in the Issue department, but I also posted the issue there: vuejs/language-tools#585

I'm just wondering if anyone else is experiencing this issue.

-

Environment

Reproduction

It say to remove incompatible and obsolete modules remove like @vue/composition-api from your dependencies.

But when try to use Pinia it say vue-composition-api is required.

WTF

Describe the bug

Nuxt bridge not work.
Nuxt 3 not work.
Nothing not work.
It's a shit!

Additional context

No response

Logs

No response

Hydration node mismatch when using snipcart <billing>

Environment

  • Operating System: Linux
  • Node Version: v16.15.0
  • Nuxt Version: 3.0.0-rc.3
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: css, build, vue, vite, meta, runtimeConfig
  • Runtime Modules: -
  • Build Modules: -

Reproduction

https://stackblitz.com/edit/github-rytvwm?file=layouts/default.vue

Describe the bug

Using Snipcart with Nuxt works well if you use it just like this

<div
  hidden
  id="snipcart"
  data-api-key="my-key-here"
></div>

But if you use an order custom field, which includes native custom elements, you get errors (the below example is from https://docs.snipcart.com/v3/setup/order-custom-fields):

<div
  hidden
  id="snipcart"
  data-api-key="my-key-here"
>
  <billing section="top">
    <fieldset class="snipcart-form__set">
      <div class="snipcart-form__field">
        <snipcart-label for="storeToPickUpFrom" class="snipcart__font--tiny">
          Store to pick-up from
        </snipcart-label>
        <snipcart-select name="storeToPickUpFrom" class="snipcart-form__select  snipcart__font--secondary snipcart__font--bold">
          <option value="1">One</option>
          <option value="2">Two</option>
          <option value="3"> Three</option>
          <option value="4">Four</option>
        </snipcart-select>
      </div>
    </fieldset>
  </billing>
</div>

It first tells you to make sure to exclude custom elements from component resolution via compilerOptions.isCustomElement, which is fine and can be handled, but then still the following problem I can't resolve:

[Vue warn]: Hydration node mismatch:
- Client vnode: billing 
- Server rendered DOM: <!---->  
  at <Default > 
  at <AsyncComponentWrapper > 
  at <BaseTransition mode="out-in" appear=false persisted=false  ... > 
  at <Transition name="layout" mode="out-in" > 
  at <Anonymous name="default" > 
  at <App key=1 > 
  at <NuxtRoot>

In the reproduction it can be seen, that it is not displayed correct. Instead of displaying it on the cart in the billing section it is displayed on the page. For the reproduction it is necessary to create a free snipcart account and paste the key into data-api-key. Hope somebody can help me out here.

Additional context

No response

Logs

No response

How define global fetch hook

Hi there!
I haven't found any correct implementation for global hooks nuxt (useasyncdata, $fetch, usefetch).
I would like to be able to configure a global hook that will have an Authorization header, base Url, proxy, etc.

Is there any good architectural solution to this issue?

Nuxt server init implementation

Hi there!

which is better way to implement nuxtServerInit in nuxtjs3?

  1. /plugins/server-init.server.ts
    export default defineNuxtPlugin(() => { console.log('CLIENT-INIT-PLUGIN'); });

  2. middleware/server-init.ts
    export default function () { if (process.server) { console.log('CLIENT-INIT-PLUGIN'); } }
    nuxt.config.ts
    { router: { middleware: ['nuxt-server-init'] } }

P.S. I'm still leaning towards option 1, but here I get warning:
[Vue warn]: onServerPrefetch is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.

nuxi generate on Windows outpus error " ERROR Only URLs with a scheme in: file, data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'"

Environment

  • Operating System: Windows_NT
  • Node Version: v17.9.0
  • Nuxt Version: 3.0.0-27491748.3186841
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: target
  • Runtime Modules: -
  • Build Modules: -

Reproduction

package.json

"scripts": {
    "generate": "nuxi generate",
  },

nuxt.config.ts

export default defineNuxtConfig({
  target: 'static',
})

When do command pnpm generate in terminal, outputs are:

> @ generate C:\Users\kamas\Apps\nuxt3-electron
> nuxi generate

Nuxt CLI v3.0.0-27491748.3186841                                                          19:43:47
i Vite client warmed up in 1273ms                                                         19:43:52
i Client built in 1635ms                                                                  19:43:53
i Building server...                                                                      19:43:53
โˆš Server built in 510ms                                                                   19:43:53
โˆš Generated public .output/public                                                   nitro 19:43:53
start Preparing prerenderer...                                                      nitro 19:43:53

 ERROR  Only URLs with a scheme in: file, data are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'

  at new NodeError (node:internal/errors:372:5)
  at throwIfUnsupportedURLScheme (node:internal/modules/esm/resolve:1075:11)
  at defaultResolve (node:internal/modules/esm/resolve:1155:3)
  at ESMLoader.resolve (node:internal/modules/esm/loader:604:30)
  at ESMLoader.getModuleJob (node:internal/modules/esm/loader:318:18)
  at ESMLoader.import (node:internal/modules/esm/loader:404:22)
  at importModuleDynamically (node:internal/modules/esm/translators:106:35)
  at importModuleDynamicallyCallback (node:internal/process/esm_loader:35:14)
  at prerender (/C:/Users/kamas/Apps/nuxt3-electron/node_modules/.pnpm/[email protected]/node_modules/nitropack/dist/chunks/prerender.mjs:2142:39)
  at async /C:/Users/kamas/Apps/nuxt3-electron/node_modules/.pnpm/[email protected]/node_modules/nuxt3/dist/index.mjs:1221:9

โ€‰ELIFECYCLEโ€‰ Command failed with exit code 1.

Many thanks for any help.

Describe the bug

This bug occurs with even the very latest version of nuxt3 (3.0.0-27491748.3186841).

Additional context

No response

Logs

No response

Nuxt 3 nitro + mikro-orm

Environment

  • Operating System: Linux
  • Node Version: v16.15.1
  • Nuxt Version: 3.0.0-rc.4
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

import { RequestContext } from '@mikro-orm/core'

import { DI } from '../data-source'

export default defineEventHandler(async (event) => {
  console.log(next)
  RequestContext.create(DI.orm.em, next) // no next function
})

OR

import { RequestContext } from '@mikro-orm/core'

import { DI } from '../data-source'

export default (req, res, next) => {
  console.log(next)
  RequestContext.create(DI.orm.em, next) // has next but not work, such error was with fastify https://github.com/fastify/fastify/issues/3570
}

DI file

import 'reflect-metadata'
import {
  // EntityManager,
  // EntityRepository,
  MikroORM
} from '@mikro-orm/core'

import { Author } from './entities'

export const DI = {} as {
  orm: MikroORM,
  // em: EntityManager,
  // authorRepository: EntityRepository<Author>
}

(async () => {
  DI.orm = await MikroORM.init({
    type: 'mariadb',
    entities: [Author],
    dbName: 'nuxt',
    password: '123456',
    user: 'admin',
    debug: true
  })
})()

Describe the bug

No next function. In legacy exist but no effect like with old version of fastify here
nestjs/nest#8837
nodejs/node#41285

[nitro] [dev] [unhandledRejection] ValidationError: Using global EntityManager instance methods for context specific actions is disallowed. If you need to work with the global instance's identity map, use allowGlobalContext configuration option or fork() instead.

Additional context

No response

Logs

No response

Route Caching rules

Server Rendering Strategies

Generally, we have several possible ways to render a route. In the table below, a summary is added. There are some similarities between these methods and to avoid confusing users for choosing the proper platform, we need a unified way of describing them and mentioning which nuxt version supports which and what are the trade-offs.

Strategy Known As Shared Cache (1)
Server-Side rendering SSR โŒ
Client-Side rendering SPA โŒ
Preview Preview โŒ
Prerendering (2) Generate, Static โœ”๏ธ
Crawling (2) Full Static โœ”๏ธ
HTTP caching SWR, HTTP Cache โœ”๏ธ
On-demand pre-rendering (2) Netlify Builder, Vercel ISR โœ”๏ธ
  • (1) With a Shared cache, we can respond regardless of user requests (Auth Headers, Cookies, IP, Browser) which makes responding faster with caching possibilities but is not always desired
  • (2) [on-demand] prerendering and crawling are simply edge-based permanent caching strategies that invalidate on each CI build
  • For strategies with Shared Cache we need to disallow specific functionalities like access to query params during development

Strategy Configuration

We need a schema to describe route/route-groups in nuxt.config with their desired rendering strategy. In addition to caching, it can be useful to describe other meta like redirect rules and password protection. One important note is that, this configuration needs to be serializable to be reusable for vendor-specific purposes.

Example:

export default defineNuxtConfig({
  routes: {
    '/': { prerender: true }, // Once per build (via builder)
    '/blog/*': { static: true }, // Once on-demand per build (via lambda)
    '/stats/*': { swr: '10 min' }, // Once on-demand each 10 minutes (via lambda)
    '/admin/*': { ssr: false }, // Client-Side rendered
    '/react/*': { redirect: '/vue' }, // Redirect Rules
  }
})

Depending on the nitro platform or in-development, we can map route configuration to proper implementation.

For the context, with nuxt2, we have these options:

  • mode / ssr: Switch on/off SSR for entire project
  • generate.routes (helping crawler and prerenderer)
  • req.spa (see Runtime Strategies)
  • static: Enable Prerender/Crawler for all routes

New routes can cover all but we can preserve them as shortcuts and compatibility

Runtime Strategies

Runtime strategies might be also possible but not working for all platforms if they need declarative configuration (like Vercel) and reduce optimization possibilities since we cannot easily predict what will happen for a specific route or if it is a request based rule or not. Yet we can partially support them for special cases (like this). Also we can have a way to infer config from pages.

Client-Side Behavior

Client Rendering behavior also depends on server Strategies:

  • For client-side rendering (CSR and SPA), we need to apply server logic before hydration
  • For Preview mode, we need to override server response (if any) and apply server-logic
  • For the crawling method, we need to fetch payload instead of normal logic
  • For SWR method, we need to revalidate Etag and reload if a mismatch happening
  • For Shared Cache methods (except Crawling), we need to ensure if there is any newer API response, gracefully handling errors.

`defineRouteMeta({})` compiler macro

Background

There are a number of use cases where we need to get information from pages.

In some cases we care about the route, not the page component specifically. For example, a child component might decide we need to render with the 'admin' layout - this is a global value. In other cases, we care specifically about the value from the page itself (e.g. a parent component might not have a key, but a child component might have a key). In these cases, we want to tie the value specifically to the component data itself.

Here are some sample use cases.

Layout information

Route-level

We need to be able to define the layout at the route level. It therefore makes sense to define this on route meta rather than directly on the component.

See nuxt/nuxt#12829 and nuxt/nuxt#11923

Transition and keepAlive props

Route-level

As above, this should be defined at route level. If we set transition props on a child route, we want this to be accesible in NuxtPage so it can be set correctly on the global <transition> element.

Note that this data isn't serialisable. For example, we can pass functions as transition options.

Middleware

Route-level

This should also be defined at route level and needs to be accessible outside of <RouterView> so we can handle it within route guards.

See https://github.com/nuxt/framework/discussions/2082

Key

Page-level

This should be set specifically on the component that needs to be keyed, rather than on route meta. We might have a shared layout or parent route that can persist between routes, but the child needs to be keyed specifically. We don't need to know the route key unless actually showing the route, which means it's safe to store within the component options.

Note that this data isn't serialisable. For example, we can pass a function that takes a route object.

User-defined metadata

Route-level

Users may wish to define metadata like page title, description, etc. These should be global rather than specific to the component, and make sense to store in the route meta object as a whole. Users may wish to know all this metadata even when not displaying the component.

Implementation

Usage within script setup

We can use compiler macros to define this data within <script setup> and make it available within router.mjs (for route-level data) and within the component options (for page-level data).

Would allow usage like:

// this will be extracted out to the route metadata within router.mjs
defineRouteMeta({
  middleware: []
})

// this will be hoisted to the options of the component
definePageKey(route => route.path)
definePageKey('fixed')

Usage with Options API

export default {
  middleware: [],
  key: route => route.path,
  // or key: 'fixed'
}

We could alternatively support using the same compiler macro as above in the Options API.

How to add additional firebase functions when deploying nuxt to firebase

Environment

  • Operating System: Darwin
  • Node Version: v16.13.1
  • Nuxt Version: 3.0.0-27324955.23397e6
  • Package Manager: [email protected]
  • Bundler: Vite
  • User Config: css, meta, vite, https, ssr
  • Runtime Modules: -
  • Build Modules: -

Reproduction

Prerequisites: A nuxt3 project, e.g. https://codesandbox.io/s/github/nuxt/starter/tree/v3-codesandbox

  • Run NITRO_PRESET=firebase npm run build

  • The firebase function for running nuxt is generated in .output/server

  • In /firebase.json the following config is set:

{
"functions": { "source": ".output/server" },
}

Info: functions.source cannot be set to multiple paths

Nuxt exports only a single function which includes the nuxt build:

/.output/server/index.mjs:

// [...]
const server = functions.https.onRequest(handle);
export { server };

Describe the bug

Not a bug but a question:

Is there a way to add/include additional firebase functions that are output to .output/server when running nuxi build?

I want to add a custom firebase function which is deployed to firebase in addition to the nuxt-function when running firebase deploy.

But the folder .output/server which contains the functions to be deployed is autogenerated by nuxi build.
This is also true for the package.json file in .output/server

I know I can also implement middleware & API endpoints in nuxt, but in my case I explicitly want to use an additional firebase function.

Additional context

This is what I want to add as a firebase function to existing nuxt3 project: https://maxbarry.medium.com/dynamic-on-demand-image-resizing-using-firebase-hosting-and-google-cloud-functions-to-make-a-cheap-d64e8f5805d1

If I forgot to add important info to this Issue, please let me know so that I can add it.

Logs

No response

nuxi build: (!) Some chunks are larger than 500 KiB after minification.

Everytime, i build it using yarn build (nuxi build), i see this warning in the console.

Why does it show it? we are just using import on overall project right?
For source code & reproduction, This is my example Project repo

 WARN                                                                                                                                                            15:32:15  
(!) Some chunks are larger than 500 KiB after minification. Consider:
- Using dynamic import() to code-split the application
- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks
- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.

NuxtLink doesn't support hook onServerPrefetch

Environment

Operating System: Windows_NT
Node Version: v16.13.0
Nuxt Version: 3.0.0-rc.3
Package Manager: [email protected]
Builder: vite
User Config: typescript
Runtime Modules: -
Build Modules: -

Reproduction

export default {
setup() {
const route = useRoute();
const catInfo = useCategoryInfo(); /this method is available in index.js/
onServerPrefetch(async () => {
await catInfo.getCatInfo(route.params.id);
});
return {
route ,
catInfo
};
}
}

Describe the bug

I'm struggling with this problem since I've been using Nuxt. I'm coding an E-commerce website using nuxt3 and vue3 and data is got from an api using Pinia, therefore SEO is so important to me and codes should be shown on Page Source. I found a way to render HTML codes on page source:

  1. executing the function which gets data from api inside onServerPrefetch hook .
  2. Wrapping the html code which gets its data from api in .

Functions inside vue onServerPrefetch will be executed well when the page is refreshed and but the problem appears when switching between routes using NuxtLink. I found that when the routes are switched using nuxtlink, the functions inside onServerPrefetch are not executed.
Possible solutions you may give me:

  1. using onMounted: This will eliminate this problem but wouldn't render data during server side rendering, so those data and html codes which are reliable to api. wouldn't be rendered in page source.
  2. using useAsyncData or useFetch: This will eliminate the problem. But I need pinia state manager to fetch data and store them

Additional context

No response

Logs

No response

State Controller

Over the time, nuxt building process became more and more complex and while there is no clear visualization of what is happening, improving user experience would be hard.

Goals of this issue:

  • Describe current flow as parallel state machines
  • Help writing internal documentation to describe how nuxt works
  • Implement unified state controller based on nuxt hooks for nu cli and dev tools for smooth and managed user experience
  • Using visualization to ensure all cases are handled in dev flow
  • Discover improvement areas

Next Steps

  • Evaluate current machines
  • Extract fsm tables (state, error and event codes)
  • Implement global controller based on FSM machine and nuxt hooks
  • Write internals documentation
  • [reevaluate issue]

Config State

image

  • Source: cli

Upon initialization or when nuxt.config is changed, this process starts. Updating config causes full nuxt restart.

Improvement areas:

  • Watch nuxt.config dependencies
  • Accept nuxt hook to manually trigger init
  • Diff from old config and use a hook to see there is a client accepting change, avoid restarting (config HMR)

Core State

image

  • Source: nuxt3

When config is (re)loaded, the core has to be initialized. It involves assigning defaults, validating config, and initializing all nuxt modules.

Improvement areas:

  • Trigger restart if a module is changed

App State

image

  • Source: nuxt3

Nuxt uses a templating engine to generate code based on project structure and config. If a file/dir is created or removed from this structure, we need to repeat generate process. This starts when the core is ready.

Improvement areas:

  • Partial generate (updating only one template)
  • Use virtual filesystem to write files

Bundler state

image

  • Source: webpack, vite

When app code is ready, we use either webpack or vite to generate client, server bundles.

Improvement areas:

  • Unify progress and error state for vite and webpack

Nitro State

image

Nitro, is the server engine for nuxt. Wrapping server code with bundle dist to make final server using rollup. For performance reasons, nitro does not wait until the bundle is ready (which involves app generation) and lazy loads bundle.

  • Source: nitro

Improvement areas:

  • Sync with bundle state to keep the user waiting instead of error (while bundle is not ready)
  • Sync with nitro state to keep user waiting instead of refresh method (while nitro is not ready)
  • Reuse the previous bundle (offline cache) if possible
  • Better sync with CLI

CLI state

Due to parallel complexities, cli is not visualized but it is how nu dev works:

  • Start a server immediately
  • Initialize core
  • Start app build
  • Replace server with nitro when ready

Improvement areas:

  • Sync with the global state (all machines above) for error control
  • Use a simple indicator to show status like ora
  • Support WebSocket upgrade
  • Keep user waiting instead of refresh workaround
  • Expose its API to build state-aware dev tools / extension

Jest is unable to consume `mjs` files imported by `@nuxt/bridge` via `#app`

Environment

Describe the bug

Jest is unable to resolve the #app import by default. Adding a moduleNameMapper and a transform option for mjs helps fix initial problems but does not ultimately resolve the issue:

module.exports = {
  moduleFileExtensions: ['js', 'ts', 'vue', 'json', 'mjs'],
  moduleNameMapper: {
    '^#app$': '@nuxt/bridge/dist/runtime/index.mjs',
    '^@/(.*)$': '<rootDir>/src/$1',
    '^~/(.*)$': '<rootDir>/src/$1',
    '^vue$': 'vue/dist/vue.common.js',
    '(.*svg)(\\?inline)$': '<rootDir>/test/unit/test-utils/svgTransform.js',
  },
  transform: {
    '^.+\\.m?[tj]s$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub',
    '^.+\\.svg$': '<rootDir>/test/unit/svg-transform.js',
  },
}

But it doesn't ultimately fix the issue. Jest will still fail like so:

 FAIL  pages/index.test.js
  โ— Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     โ€ข If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     โ€ข To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     โ€ข If you need a custom transformation specify a "transform" option in your config.
     โ€ข If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /sandbox/node_modules/@nuxt/bridge/dist/runtime/index.mjs:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './app.mjs'
                                  ^^^^^^

    SyntaxError: Unexpected token 'export'

      4 |
      5 | <script>
    > 6 | import { ref } from "#app";
        | ^
      7 | export default {
      8 |   setup() {
      9 |     const foo = ref(0);

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at pages/index.vue:6:1
      at Object.<anonymous> (pages/index.vue:25:3)

@nuxt/bridge could publish regular js files to be used by jest. Or else some advice for how to resolve this and make it possible for jest to run with @nuxt/bridge would be very helpful and welcome.

Reproduction

https://codesandbox.io/s/adoring-moore-q87xq

Open a new terminal in that code sandbox and run yarn test and observe the error related to importing @nuxt/bridge

Additional context

No response

Logs

No response

How to use global mixins in nuxt 3

Hey I'm trying to import and add a global mixin file to be used on all pages, but the technique I used in Nuxt 2 doesn't seem to be available in Nuxt 3. The reason I want to add a global mixin file is so that I have access to functions I'll use on almost every page without having to import the mixin each time.

Here is what I have done in the past in either my app.vue file or my layouts/default.vue file depending on my file structure:

import Vue from 'vue'
import globalMixin from '~/mixins/globalMixin.js'

Vue.mixin(globalMixin)

When I attempt to do this in Nuxt 3, I get the error 'Cannot read property mixin of undefined'.

After some experimentation I was able to change my import so that it worked with es6 by doing import * as Vue from 'vue'. This solved the issue above, but when I tried to do the same command above Vue.mixin(globalMixin) I got a new error 'vite_ssr_import_0.mixin is not a function'. Can anybody help me add a global mixin or is there another more effective way to make a group of functions available globally?

Docs: server endpoint post example

I'm using Nuxt-Bridge in a Nuxt 2 project.

I have implemented a custom API endpoint that is only active in development to get around CORS. This was done using serverMiddleware, I can't see any way in the docs to set an endpoint to accept a only post request. Is this feature currently available?

Server middleware

const axios = require('axios')
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.post('/', async function (req, res) {
  const response = await axios.post('https://someUrl.com/myEndpoint', req.body, { auth: { username: 'myUser', password: 'myPassword' } })
  return res.status(response.status).send(response.data)
})

module.exports = {
  path: '/apiProxy/',
  handler: app
}

nuxt.config.js :

const config = {
  serverMiddleware: []
}

// Development configuration
if (process.env.NODE_ENV === 'development') {
  config.server = {
    port: 3000,
    host: '0.0.0.0'
  }
  config.serverMiddleware = [
    { path: '/apiProxy', handler: '~/apiProxy/index.js' }
  ]
}

export default {
  serverMiddleware: config.serverMiddleware
  // rest of the nuxt config
}

npx nuxi init error

Environment


  • Operating System: Darwin
  • Node Version: v16.11.0
  • Nuxt Version: 0.0.0
  • Package Manager: unknown
  • Bundler: Webpack
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

Reproduction is unavailable. The bug is on bootstrap level.

Describe the bug

When trying to create a new nuxt project with npx nuxi init following error shown

Nuxt CLI v3.0.0-27284664.232fdd8

WARN could not fetch remote https://github.com/nuxt/starter

WARN Make sure you have installed git correctly

Additional context

git installed - git version 2.26.0

internet connection works

Logs

No response

How can i get client's ip address when fetch data?

Environment


  • Operating System: Windows_NT
  • Node Version: v16.14.0
  • Nuxt Version: 3.0.0-rc.1
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: runtimeConfig
  • Runtime Modules: -
  • Build Modules: -

๐Ÿ‘‰ Report an issue: https://github.com/nuxt/framework/issues/new 17:22:54

๐Ÿ‘‰ Suggest an improvement: https://github.com/nuxt/framework/discussions/new

๐Ÿ‘‰ Read documentation: https://v3.nuxtjs.org

Reproduction

just installed / pure nuxt 3

Describe the bug

how can i get client's ip address when fetch data?

it works when data fetching on client side but not server side

i tried this

* ~/page/index.vue
<script lang="ts" setup>

  const test1 = await useAsyncData('key', async (app) => {
    console.log(app.ssrContext.event.req.connection.remoteAddress || app.ssrContext.event.req.socket.remoteAddress)
   // console.log => empty string
    return []
  })

  const test2 = useFetch('/api/test', {
    headers: useRequestHeaders(['cookie', 'x-forwarded-for']),
  }) // for check ip from ~/server/api/test.ts

</script>
* ~/server/api/test.ts
export default defineEventHandler(async ({ req, res, context, event }) => {
   console.log(
       req.socket.remoteAddress,
       req.connection.remoteAddress,
       req.headers['x-forwarded-for'],
     ) // it all returns empty string or undefined until request is not from browser(client)
   return []
})

both failed to read client's ip..
please let me know if i missed something. thanks

Additional context

No response

Logs

No response

Custom directive

Hello, tell me how to rewrite the directive for Nuxt 3?

import Vue from 'vue'

Vue.directive('click-outside', {
  bind(el: any, binding: any) {
    el.addEventListener('click', (e: any) => e.stopPropagation())
    document.body.addEventListener('click', binding.value)
  },
  unbind(_, binding: any) {
    document.body.removeEventListener('click', binding.value)
  },
})

When building an absolutely clean project, it contains a css file with 500+ lines of code, where does it come from?!

Environment


  • Operating System: Windows_NT
  • Node Version: v16.14.2
  • Nuxt Version: 3.0.0-rc.1
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

Only one file - app.vue, no css files or components

<template>
  <div>
    <h1>Hello world</h1>
  </div>
</template>

Describe the bug

When you build the project, a css file appears in the .output > public > _nuxt folder,
containing more than 500 lines of code, as far as I understand, these are tailwindcss classes.
But there is not a single css file or component with styles in the project.

Additional context

No response

Logs

No response

Devtools: In dev mode getting "Devtools inspection is not available because it's in production mode or explicitly disabled by the author"

Environment

Nuxt project info:


  • Operating System: Darwin
  • Node Version: v16.12.0
  • Nuxt Version: 3.0.0-27307420.6a25d3e
  • Package Manager: [email protected]
  • Bundler: Vite
  • User Config: buildModules, dev, build, intlify, publicRuntimeConfig
  • Runtime Modules: -
  • Build Modules: @intlify/[email protected]

Reproduction

n/a

Describe the bug

Starting nuxt with yarn dev or yarn dev --devtools, with or without dev: true in config, in any case getting from vue devtools:

Nuxt.js + Vue.js is detected on this page.
Devtools inspection is not available because it's in production mode or explicitly disabled by the author.

Additional context

No response

Logs

No response

[Deployment] File .env not using

Environment

Nuxt CLI v3.0.0-27376943.f219f63 14:39:55
RootDir: /Users/nickleus/Documents/projects.nosync/com.atrap.io/project 14:39:57
Nuxt project info: 14:39:57


  • Operating System: Darwin
  • Node Version: v16.12.0
  • Nuxt Version: 3.0.0-27376943.f219f63
  • Package Manager: [email protected]
  • Bundler: Vite
  • User Config: srcDir, css, build, privateRuntimeConfig, vite
  • Runtime Modules: -
  • Build Modules: -

Reproduction

Hello,

I am testing the deployment on Firebase with nuxt3 in SSR

At the root of the project I have an .env file with a value in it.

ENV_VARIABLE=string

In nuxt.config.ts

import { defineNuxtConfig } from 'nuxt3'

export default defineNuxtConfig({
    privateRuntimeConfig: {
      VARIABLE: process.env.ENV_VARIABLE
    },
})

To execute the Deployment on the hosting of the emulator, I have the command local : yarn local

  "private": true,
  "scripts": {
    "build": "nuxi build",
    "clean": "rm -rf .nuxt/ .output/ node_modules/",
    "preset": "NITRO_PRESET=firebase yarn build", <-- As stated in the documentation
    "local": "yarn clean && yarn && yarn preset && firebase emulators:start",
  },
  "devDependencies": {
    "nuxt3": "latest"
  },
}

I use this variable in nuxtjs api

A folder /server/api/folder/file.js

with the following code to test:

export default async (req, res) => {
  return process.env;
}

Describe the bug

The VARIABLE environment variable is not present in the list.

Additional context

No response

Logs

Aucun log

Isomorphic fetch doesnt set cookies

Environment


  • Operating System: Linux
  • Node Version: v16.14.0
  • Nuxt Version: 3.0.0-rc.0-27508091.78fcbcf
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: runtimeConfig, buildModules, modules, tailwindcss, app, nitro, build, modern
  • Runtime Modules: @nuxtjs/[email protected]
  • Build Modules: @vueuse/[email protected]

Reproduction

Describe the bug

I want to make my own universal fetch, which would automatically send the token stored in the client's cookies
And if the token is invalid, it was automatically updated
What i have:
@/composables/useRequest.ts

export async function useRequest<T>(
	url: string,
	options: { method?: 'GET' | 'POST'; body?: {}; headers?: HeadersInit } = {
		body: null,
		method: 'GET',
	},
) {
	return await $fetch(url, options).catch(async (e) => {
		if (!e?.message?.includes('401')) throw e;

		const response = await $fetch.raw<IServerResponse<string>>('/api/auth/refresh', {
			headers: options.headers,
		});

		if (process.server) {
			const cookies = Object.fromEntries(
				response.headers
					.get('set-cookie')
					?.split(',')
					.map((a) => a.split('=')),
			);

			const cookieName = 'access';

			if (cookieName in cookies) {
				const newCookie = cookies[cookieName]?.split(';')[0];
				useCookie(cookieName, { maxAge: 7 * 24 * 60 * 60 }).value = newCookie;
			}
		}
		// return await $fetch<T>(url, options);
	});
}

on the server side in apiroutes i set new cookies like this:
setCookie(event, 'access', tokens.accessToken, { maxAge: 7 * 24 * 60 * 60 });

the most incomprehensible thing for me - is in this line:
@/composables/useRequest.ts

if (cookieName in cookies) {
	console.log('\n useRequest SERVER_SIDE COOKIES :::', cookies[cookieName]);
	const newCookie = cookies[cookieName]?.split(';')[0];
	useCookie(cookieName, { maxAge: 7 * 24 * 60 * 60 }).value = newCookie;
	console.log('\n useRequest SERVER_SIDE useCookie :::', useCookie(cookieName).value); // [THIS ROW]
}

[THIS ROW] never be shown in my server console...
and ofc i dont have new cookies at my client side

Additional context

No response

Logs

No response

How to deploy to Netlify or Vercel between a pnpm workspace

Discussed in https://github.com/nuxt/framework/discussions/4943

Originally posted by alvarosabu May 12, 2022
Hi, there community,

I'm working on a pnpm workspace monorepo which contains a Nuxt v3.0.0-rc.3 app that I want to deploy to Netlify | Vercel.

I'm facing an issue on build ci on both platforms, "Failed to resolve" multiple packages including vue and ufo https://app.netlify.com/sites/alvarosabu-next/deploys/627caac87fa81c000876ba1c

Locally the build is successful

I honestly don't know if it's a Nuxt issue, a Netlify|Vercel one, pnpm, of all. I will appreciate some feedback.

Thanks

Netlify config

[build.environment]
  NODE_VERSION = "16"
  NPM_FLAGS = "--version" # prevent Netlify npm install
[build]
  publish = "apps/portfolio/.output/public"
  command = "npx pnpm@6 i --store=node_modules/.pnpm-store --frozen-lockfile && npx pnpm@6 run build:ci"

Related scripts

"build:ci": "pnpm build:ui && pnpm run generate:portfolio",
"generate:portfolio": "pnpm run generate --filter @alvarosabu/portfolio",
 "build:ui": "pnpm run build --filter @alvarosabu/ui"

Error log

[log] Nuxt CLI v3.0.0-rc.3
8:20:12 AM: [error] Failed to resolve force included dependency: vue
8:20:12 AM: [error] Failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs". Does the file exist?
8:20:12 AM: [error] Failed to resolve import "vue" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/components.plugin.mjs". Does the file exist?
8:20:12 AM: [error] Failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs". Does the file exist?
8:20:12 AM: [error] Failed to resolve import "vue" from "app.vue". Does the file exist?
8:20:12 AM: [error] Failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs". Does the file exist?
8:20:13 AM: [error] Failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs". Does the file exist?
8:20:13 AM: [error] Failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs". Does the file exist?
8:20:13 AM: [error] Failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs". Does the file exist?
8:20:13 AM: [error] Failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs". Does the file exist?
8:20:13 AM: [error] [vite]: Rollup failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs".
8:20:13 AM: This is most likely unintended because it can break your application at runtime.
8:20:13 AM: If you do want to externalize this module explicitly add it to
8:20:13 AM: `build.rollupOptions.external`
8:20:13 AM: [error] [vite]: Rollup failed to resolve import "ufo" from "virtual:nuxt:/opt/build/repo/apps/portfolio/.nuxt/paths.mjs".
8:20:13 AM: This is most likely unintended because it can break your application at runtime.
8:20:13 AM: If you do want to externalize this module explicitly add it to
8:20:13 AM: `build.rollupOptions.external`
8:20:13 AM:   This is most likely unintended because it can break your application at runtime.
8:20:13 AM:   If you do want to externalize this module explicitly add it to
8:20:13 AM:   `build.rollupOptions.external`
8:20:13 AM:   at onRollupWarning (/opt/build/repo/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-e1fc1d62.js:41550:19)
8:20:13 AM:   at onwarn (/opt/build/repo/node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-e1fc1d62.js:41366:13)
8:20:13 AM:   at Object.onwarn (/opt/build/repo/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:23184:13)
8:20:13 AM:   at ModuleLoader.handleResolveId (/opt/build/repo/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:22474:26)
8:20:13 AM:   at /opt/build/repo/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:22435:26
8:20:13 AM: undefined
8:20:13 AM: /opt/build/repo/apps/portfolio:
8:20:13 AM: โ€‰ERR_PNPM_RECURSIVE_RUN_FIRST_FAILโ€‰ @alvarosabu/[email protected] generate: `nuxt generate`
8:20:13 AM: Exit status 1
8:20:13 AM: โ€‰ELIFECYCLEโ€‰ Command failed with exit code 1. (https://ntl.fyi/exit-code-1)
8:20:13 AM: โ€‰ELIFECYCLEโ€‰ Command failed with exit code 1. (https://ntl.fyi/exit-code-1)
8:20:13 AM: โ€‹
8:20:13 AM: โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
8:20:13 AM:   "build.command" failed                                        
8:20:13 AM: โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
8:20:13 AM: โ€‹
8:20:13 AM:   Error message
8:20:13 AM:   Command failed with exit code 1: npx pnpm@6 i --store=node_modules/.pnpm-store --frozen-lockfile && npx pnpm@6 run build:ci (https://ntl.fyi/exit-code-1)
8:20:13 AM: โ€‹
8:20:13 AM:   Error location
8:20:13 AM:   In build.command from netlify.toml:
8:20:13 AM:   npx pnpm@6 i --store=node_modules/.pnpm-store --frozen-lockfile && npx pnpm@6 run build:ci
8:20:13 AM: โ€‹
```</div>

how to add variables of process.env in nuxt3 ?

Environment

nuxt3 ^3.0.0-27243104.5e903ae
mac

Describe the bug

I try all the methods but not success

Reproduction

I find some solutions like #1086 but not success

Additional context

No response

Logs

No response

Accessing remote IP in <script setup>

Environment

Nuxt project info: 16:35:43


  • Operating System: Linux
  • Node Version: v17.0.0
  • Nuxt Version: 3.0.0-27460489.53fbca7
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: serverMiddleware
  • Runtime Modules: -
  • Build Modules: -

Reproduction

// Only one file "app.vue" can reproduce the issue


<script setup lang="ts">
enum Gender {
  GIRL = 'Girl',
      BOY = 'Boy',
      UNISEX = 'Unisex'
}
const options = reactive({
  gender: 'Girl',
});

const app = useNuxtApp()
const ipAddress = app.ssrContext.req.socket.remoteAddress
</script>
<template>
<div>
  <button v-for="(genderType,idx) in Gender" :key="idx" @click="options.gender=genderType" :class="{active: genderType==options.gender}">{{genderType}}</button>
  <button>Not effected</button>
</div>
</template>

<style scoped>
  .active {
    background: rgb(255, 77,23)
  }
</style>

Describe the bug

Development Environment

When the code is executed in dev mode, it will cause that the 3 buttons "Girl", "Boy", "Unisex" being not interactive
If you try to comment the line:
const ipAddress = app.ssrContext.req.socket.remoteAddress
The website will work normally
There might be exception happening while trying to access ip Address "returns undefined in dev mode"
I tried accessing ip address in server route and the elements are not getting effected
Also, the fourth button of title "Not effected", may not get effected anyway
If you may try adding checkbox with v-model, It is not effected
But in my case, buttons with reactive or ref as I have also tried will + v-for on enum and change value inside ref or reactive when @click will hang up if you try accessing ip address from nuxt ssr context inside <script setup>

Production Environment

In production mode, the four buttons will be rendered normally:
<button class="active" data-v-6a8b2cd5>Girl</button><button class="" data-v-6a8b2cd5>Boy</button><button class="" data-v-6a8b2cd5>Unisex</button><!--]--><button data-v-6a8b2cd5>Not effected</button>
But once the page is loaded, 3 buttons will be hidden and remains 1 buttons with class "active" visible
If you try removing button "Not Effected" then 3 buttons are normally rendered:
<button class="active" data-v-a4bb4f60>Girl</button><button class="" data-v-a4bb4f60>Boy</button><button class="" data-v-a4bb4f60>Unisex</button>
But they are all hidden before and after the page complete loading

Additional context

No response

Logs

No response

API router throwing error with large files

Environment


  • Operating System: Linux
  • Node Version: v16.14.0
  • Nuxt Version: 3.0.0-rc.0-27508091.78fcbcf
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: runtimeConfig, buildModules, modules, tailwindcss, app, nitro, build, modern
  • Runtime Modules: @nuxtjs/[email protected]
  • Build Modules: @vueuse/[email protected]

Reproduction

https://stackblitz.com/edit/github-tjflbh?file=app.vue

Reproduction does not allow opening files
Therefore, there is only a structure

Describe the bug

When i'm trying to upload from client to server the large file - i'm getting error:

ERROR  [h3] write EPIPE
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16)

Additional context

No response

Logs

No response

Is nuxt 3 mature enough for production in this time?

Hi, I am working on Vue for several years. I want to move my Vue project to Nuxt but I see Nuxt 3 is already released. Nuxt 2 is available but as I convert my frontend I want to build by the latest version. Is nuxt 3 mature enough for production? If not, when it will release the final public version?

h3 server looses cookies on page-load/page-reload

Environment

  • Operating System: Linux OS/Fedora
  • Node Version: v16.11.0
  • Nuxt Version: 3.0.0-27385241.dcc0c9
  • Package Manager: [email protected]
  • Bundler: Vite

Reproduction

nil

Describe the bug

Having a page where I need to get user's session/cookie data from the server/backend:
Firstly, on SSR, there is no Cookie on useNuxtApp().ssrContext.req.headers! (This would have sufficed for my use case)

secondly, I tried a workaround option like this

// server/api/student/reqister
import type { IncomingMessage, ServerResponse } from 'http'
import { setCookie } from 'h3

export default async (req: IncomingMessage, res: ServerResponse) => {
  const body = await useBody(req)
  // do a db operation that returns an object containing registered student
  const { registeredStudent } = await AddStudent(body)
   setCookie(res, 'registeredStudent', JSON.stringify(registeredStudent))
  return registeredStudent
}

// server/api/student/get-data
import type { IncomingMessage, ServerResponse } from 'http'
import { useCookies } from 'h3

export default async (req: IncomingMessage, res: ServerResponse) => {
  return useCookies(req)
}

// pages/student/confirm-user-registration
<script setup lang="ts">
const { data } =  await useAsyncData('get-user-data', () => $fetch('/api/student/get-data'))
console.log(data.value) 
// this works on router navigation within the browser
// But it doesn't work on page reload 
</script>

I need to get the data before Vue renders the page

Additional context

No response

Logs

No response

firebase v9 not work in dev mode (No Firebase App '[DEFAULT]')

Environment

Nuxt CLI v3.0.0-27415326.3c563fa
RootDir: /Users/niklvov/Projects/fj_web_boilerplate
Nuxt project info:


  • Operating System: Darwin
  • Node Version: v16.14.0
  • Nuxt Version: 3.0.0-27415326.3c563fa
  • Package Manager: [email protected]
  • Bundler: Vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

I want to create a firebase plugin that provides auth module

npm i firebase

// nuxt.config.ts
import { defineNuxtConfig } from 'nuxt3'

export default defineNuxtConfig({})


// plugins/firebase.ts
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'

export default defineNuxtPlugin(() => {
  // if you have a firebase project you can pass your credentials, for minimal reproduction see notes below
  initializeApp({ }) 
  return {
    provide: {
      auth: getAuth()
    }
  }
})

Then i run npx nuxi dev, and open http://localhost:3000.
In server console I get this error:

Nuxt CLI v3.0.0-27415326.3c563fa

> Local:    http://localhost:3000/
> Network:  http://192.168.1.121:3000/

โ„น Vite warmed up in 838ms
โ„น Vite warmed up in 2272ms
โœ” Vite server built in 5550ms
โœ” Nitro built in 780 ms

Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
  at getApp (file://./node_modules/@firebase/app/dist/esm/index.esm2017.js:459:29)
  at Module.getAuth (file://./node_modules/@firebase/auth/dist/node-esm/index-2bbaab7c.js:5980:24)
  at file://./.nuxt/dist/server/server.mjs:2170:35
  at callWithNuxt (file://./.nuxt/dist/server/server.mjs:262:20)
  at applyPlugin (file://./.nuxt/dist/server/server.mjs:213:29)
  at Module.applyPlugins (file://./.nuxt/dist/server/server.mjs:223:11)
  at async createNuxtAppServer (file://./.nuxt/dist/server/server.mjs:51:5)
  at async renderToString (file://./node_modules/vue-bundle-renderer/dist/index.mjs:247:19)
  at async renderMiddleware (file://./.nuxt/nitro/index.mjs:206:20)
  at async handle (file://./node_modules/h3/dist/index.mjs:601:19)

Even if i pass corrent config into initializeApp if fails to with same error.

But if I run npx nuxi build && npx nuxi preview and open http://localhost:3000.
In server console I get different error:

Nuxt CLI v3.0.0-27415326.3c563fa

โ„น Node.js version: 16.14.0
โ„น Preset: server
โ„น Working dir: .output
โ„น Starting preview command: node ./server/index.mjs
Listening on http://localhost:3000/

Firebase: Error (auth/invalid-api-key).
  at createErrorInternal (file://./server/node_modules/@firebase/auth/dist/node-esm/index-2bbaab7c.js:466:40)  
  at _assert (file://./server/node_modules/@firebase/auth/dist/node-esm/index-2bbaab7c.js:470:15)  
  at file://./server/node_modules/@firebase/auth/dist/node-esm/index-2bbaab7c.js:5919:13  
  at Component.instanceFactory (file://./server/node_modules/@firebase/auth/dist/node-esm/index-2bbaab7c.js:5936:11)  
  at Provider.getOrInitializeService (file://./server/node_modules/@firebase/component/dist/esm/index.esm2017.js:290:39)  
  at Provider.initialize (file://./server/node_modules/@firebase/component/dist/esm/index.esm2017.js:234:31)  
  at initializeAuth (file://./server/node_modules/@firebase/auth/dist/node-esm/index-2bbaab7c.js:584:27)  
  at getAuth (file://./server/node_modules/@firebase/auth/dist/node-esm/index-2bbaab7c.js:5985:12)  
  at file://./server/chunks/app/server.mjs:3254:13  
  at callWithNuxt (file://./server/chunks/app/server.mjs:335:20)

Error is different.
And if i pass correct config into initializeApp it did not fails at all.
This marks that production build code is working properly and dev code not.

Describe the bug

Nuxt3 fails in dev mode with firebase-js-sdk module.
Production build is works as expected.

Additional context

No response

Logs

No response

GSAP ScrollTrigger cannot be imported as module in build

Environment

Nuxt CLI v3.0.0-27383920.81ee59c
Nuxt project info:


  • Operating System: Darwin
  • Node Version: v17.3.1
  • Nuxt Version: 3.0.0-27383920.81ee59c
  • Package Manager: [email protected]
  • Bundler: Vite
  • User Config: build
  • Runtime Modules: -
  • Build Modules: -

Reproduction

npm i gsap

<script setup lang="ts">
import {gsap} from 'gsap'
// even though importing gsap like "import gsap from 'gsap'"
// is valid, it throws the error gsap.registerPlugin is not a function
// when running the production build
import ScrollTrigger from 'gsap/dist/ScrollTrigger'
// over here, the error is "Did you mean to import gsap/dist/ScrollTrigger.js?"
// Once it's done, it works, but there no longer is any typescript support
gsap.registerPlugin(ScrollTrigger)
</setup>

Describe the bug

Build errors

Additional context

No response

Logs

No response

[unhandledRejection] Invalid value used as weak map key

Environment


  • Operating System: Linux
  • Node Version: v16.11.0
  • Nuxt Version: 3.0.0-rc.1
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: target, modern, head, css, plugins, components, buildModules, modules, tailwindcss, sitemap, build, server, generate, router, vite
  • Runtime Modules: @nuxtjs/[email protected]
  • Build Modules: -

Reproduction

Not yet available

Describe the bug

Hello forks,

Currently, I am trying to convert one of my project written in Nuxt 2 into Nuxt 3. The project is running in yarn dev pretty well but
when I tried to build the project, it's throwing some error and exit without giving any proper way to debug.

Here is the log I received when trying to generate the project for static hosting:

$ nuxi generate
Nuxt CLI v3.0.0-rc.1                                                                                                                                                                                    21:52:29
โ„น Vite client warmed up in 2401ms                                                                                                                                                                       21:52:36

 WARN                                                                                                                                                                                                   21:52:45
(!) Some chunks are larger than 500 KiB after minification. Consider:
- Using dynamic import() to code-split the application
- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/guide/en/#outputmanualchunks
- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.

โ„น Client built in 11415ms                                                                                                                                                                               21:52:45
โ„น Building server...                                                                                                                                                                                    21:52:45
โœ” Server built in 1528ms                                                                                                                                                                                21:52:47
โœ” Generated public .output/public                                                                                                                                                                 nitro 21:52:47
โ„น Initializing prerenderer                                                                                                                                                                        nitro 21:52:47
โ„น Prerendering 1 initial routes with crawler                                                                                                                                                      nitro 21:52:50
  โ”œโ”€ / (232ms)                                                                                                                                                                                    nitro 21:52:51
  โ”œโ”€ /blog/ (8ms) (Error: [404] )                                                                                                                                                                 nitro 21:52:51
  โ”œโ”€ /about/ (7ms)                                                                                                                                                                                nitro 21:52:51
  โ”œโ”€ /contact/ (7ms)                                                                                                                                                                              nitro 21:52:51

 ERROR  [unhandledRejection] Invalid value used as weak map key                                                                                                                                         21:52:51

  at WeakMap.set (<anonymous>)
  at normalizePropsOptions (.nuxt/prerender/chunks/index.mjs:4630:11)
  at createComponentInstance (.nuxt/prerender/chunks/index.mjs:7486:23)
  at renderComponentVNode (.nuxt/prerender/chunks/index.mjs:9919:22)
  at Object.ssrRenderComponent (.nuxt/prerender/chunks/index.mjs:10351:12)
  at .nuxt/prerender/chunks/app/server.mjs:8370:39
  at renderFnWithContext (.nuxt/prerender/chunks/index.mjs:2379:21)
  at Object.ssrRenderSlot (.nuxt/prerender/chunks/index.mjs:10363:21)
  at _sfc_ssrRender$o (.nuxt/prerender/chunks/app/server.mjs:5860:26)
  at renderComponentSubTree (.nuxt/prerender/chunks/index.mjs:9991:13)

  โ”œโ”€ /privacy/ (9ms)                                                                                                                                                                              nitro 21:52:51
  โ”œโ”€ /disclaimer/ (10ms)                                                                                                                                                                          nitro 21:52:51
                                                                                                                                                        nitro 21:52:51
โœ” You can now deploy .output/public to any static hosting!                                                                                                                                              21:52:51
Done in 21.50s.

Note: I have deleted some file from pages directory for debugging purpose that's why 404 is printing in the log.

So, anyone know what's going on here?

Additional context

No response

Logs

No response

srcdir dynamic change value

hi,i have a question
I want to develop some templates in an application , not theme
A client use our application sets one template as the default template
B client use our application sets one template as the default template
I tried toggling srcDir different values in nuxt.config.ts ,its working
But how do you get this value by client data from database
How do I implement it or do I need to use other framework , like template engine?
thanks

tailwind jit doesn't work for classes in `app.vue`

Environment

Nuxt project info: 17:33:03
- Operating System: Windows_NT
- Node Version: v14.17.6
- Nuxt Version: 3.0.0-27245396.550a9f2
- Package Manager: npm
- Bundler: Vite
- User Config: buildModules, build
- Runtime Modules: -
- Build Modules: @pinia/[email protected]

Describe the bug

the 2xl:container class isn't generated when in app.vue otherwise fine.

<template>
  <div class="2xl:container mx-auto">
    <NuxtPage />
  </div>
</template>

<script lang="ts">
import "./assets/scss/tailwind.scss";
import { defineComponent } from "vue";
export default defineComponent({
  setup() {
    return {};
  },
});
</script>

Reproduction

package.json

{
  "private": true,
  "scripts": {
    "dev": "nuxt dev",
    "build": "nuxt build",
    "start": "node .output/server/index.mjs"
  },
  "devDependencies": {
    "autoprefixer": "^10.3.7",
    "nuxt3": "3.0.0-27245396.550a9f2",
    "postcss": "^8.3.11",
    "sass": "^1.43.2",
    "sass-loader": "^12.2.0",
    "tailwindcss": "^2.2.17"
  },
  "dependencies": {
    "@headlessui/vue": "0.0.0-dev.9f638c9",
    "@pinia/nuxt": "0.0.7",
    "@tailwindcss/aspect-ratio": "^0.3.0",
    "@tailwindcss/line-clamp": "^0.2.2",
    "@vueuse/core": "^6.7.3",
    "pinia": "^2.0.0-rc.14"
  }
}

nuxt.config.ts

import { defineNuxtConfig } from "nuxt3";

export default defineNuxtConfig({
  buildModules: ["@pinia/nuxt"],
  build: {
    postcss: {
      postcssOptions: {
        plugins: {
          tailwindcss: {},
          autoprefixer: {},
        },
      },
    },
    transpile: ["@headlessui/vue"],
  },
});

tailwind.config.js

const defaultTheme = require("tailwindcss/defaultTheme");
module.exports = {
  mode: "jit",
  purge: [
    "./components/**/*.{vue,js}",
    "./layouts/**/*.vue",
    "./pages/**/*.vue",
    "./plugins/**/*.{js,ts}",
    "./nuxt.config.{js,ts}",
  ],
  theme: {
    extend: {
      colors: {
        primary: ({ opacityVariable, opacityValue }) => {
          if (opacityValue !== undefined) {
            return `rgba(var(--color-primary), ${opacityValue})`;
          }
          if (opacityVariable !== undefined) {
            return `rgba(var(--color-primary), var(${opacityVariable}, 1))`;
          }
          return `rgb(var(--color-primary))`;
        },
        secondary: ({ opacityVariable, opacityValue }) => {
          if (opacityValue !== undefined) {
            return `rgba(var(--color-secondary), ${opacityValue})`;
          }
          if (opacityVariable !== undefined) {
            return `rgba(var(--color-secondary), var(${opacityVariable}, 1))`;
          }
          return `rgb(var(--color-secondary))`;
        },
      },
    },
  },
  variants: {
    extend: {},
  },
  plugins: [require("@tailwindcss/aspect-ratio"), require("@tailwindcss/line-clamp")],
};

Additional context

No response

Logs

No response

JS-IPFS failure to bundle with Vite(also webpack but Vite is the goal)

Environment

  • Operating System: Linux
  • Node Version: v16.11.1
  • Nuxt Version: 3.0.0-rc.3
  • Package Manager: [email protected]
  • Builder: vite
  • User Config: -
  • Runtime Modules: -
  • Build Modules: -

Reproduction

npx nuxi init nuxt-app \
cd nuxt-app \
yarn install \
yarn add ipfs-core \
mkdir pages plugins \

  • nuxt-app/app.vue; replace NuxtWelcome with NuxtPage
  • nuxt-app/pages/index.vue; This is just here to enable the router(the following plugins file wouldn't work without router enabled). Just a vanilla template, no script, maybe a p tag or something
  • nuxt-app/plugins/ipfs.ts; looks like this

`

import {create} from 'ipfs-core'

export default defineNuxtPlugin(() => {
return {
  provide: {
    ipfs: () => create()
  }
}
})

`

yarn dev -o

Describe the bug

Without using the plugin anywhere, just importing the module and creating the js-ipfs node triggers a weird loop. The following happens if implemented with pinia instead of using a plugin as well. To avoid the loop and just see the single error skip the -o in yarn dev.

Output:

โœ˜ [ERROR] Could not resolve "electron"

node_modules/electron-fetch/lib/index.es.js:1257:21:
  1257 โ”‚   electron = require('electron');
       โ•ต                      ~~~~~~~~~~

You can mark the path "electron" as external to exclude it from the bundle, which will remove this
error. You can also surround this "require" call with a try/catch block to handle this failure at
run-time instead of bundle-time.

ERROR 4:40:05 PM [vite] error while updating dependencies: 16:40:05
Error: Build failed with 1 error:
node_modules/electron-fetch/lib/index.es.js:1257:21: ERROR: Could not resolve "electron"
at failureErrorWithLog (/home/foss/gits/nuxt-app/node_modules/esbuild/lib/main.js:1603:15)
at /home/foss/gits/nuxt-app/node_modules/esbuild/lib/main.js:1249:28
at runOnEndCallbacks (/home/foss/gits/nuxt-app/node_modules/esbuild/lib/main.js:1034:63)
at buildResponseToResult (/home/foss/gits/nuxt-app/node_modules/esbuild/lib/main.js:1247:7)
at /home/foss/gits/nuxt-app/node_modules/esbuild/lib/main.js:1356:14
at /home/foss/gits/nuxt-app/node_modules/esbuild/lib/main.js:666:9
at handleIncomingPacket (/home/foss/gits/nuxt-app/node_modules/esbuild/lib/main.js:763:9)
at Socket.readFromStdout (/home/foss/gits/nuxt-app/node_modules/esbuild/lib/main.js:632:7)
at Socket.emit (node:events:390:28)
at Socket.emit (node:domain:475:12)

ERROR Vite Error, /_nuxt/node_modules/.vite/deps/ipfs-core.js?v=0a934655 optimized info should be defined 16:40:05

If I try doing yarn add electron (which I don't think I need) the following happens with more messages saying"optimized info should be defined" for other deps;

โœ˜ [ERROR] No matching export in "browser-external:url" for import "parse"

node_modules/electron-fetch/lib/index.es.js:1:9:
  1 โ”‚ import { parse, format, resolve } from 'url';
    โ•ต          ~~~~~

โœ˜ [ERROR] No matching export in "browser-external:url" for import "format"

node_modules/electron-fetch/lib/index.es.js:1:16:
  1 โ”‚ import { parse, format, resolve } from 'url';
    โ•ต                 ~~~~~~

โœ˜ [ERROR] No matching export in "browser-external:url" for import "resolve"

node_modules/electron-fetch/lib/index.es.js:1:24:
  1 โ”‚ import { parse, format, resolve } from 'url';
    โ•ต                         ~~~~~~~

โœ˜ [ERROR] No matching export in "browser-external:http" for import "STATUS_CODES"

node_modules/electron-fetch/lib/index.es.js:3:9:
  3 โ”‚ import { STATUS_CODES } from 'http';
    โ•ต          ~~~~~~~~~~~~

โœ˜ [ERROR] No matching export in "browser-external:stream" for import "PassThrough"

node_modules/electron-fetch/lib/index.es.js:6:17:
  6 โ”‚ import Stream, { PassThrough } from 'stream';
    โ•ต                  ~~~~~~~~~~~

Additional context

I've also tried disabling Vite for Webpack5 with no luck, that produces a different set of errors, besides I'd like to get this working in Vite.

I've taken a look at this repository but also had no luck; https://github.com/DougAnderson444/ipfs-vite-svelte-kit

Can provide more info on why that failed if requested. I thought Vite used esbuild under the hood anyway so I'm not sure why that repo was even needed to adapt ipfs-core for vite.

I've previously built projects with Nuxt2 using ipfs-core in the 2020-2021 without issue. Pretty sure this because I'm using all fairly new tooling and RC builds of those tools, but if anyone has any insight into why this may be happening I would greatly appreciate it.

Logs

No response

How do i disable SSR for a particular route?

Environment

latest

Describe the bug

ssr:false not work.

Reproduction

nuxt.config.ts

import { defineNuxtConfig } from 'nuxt3'

export default defineNuxtConfig({
// not work
  routers: {
    '/news': {
       ssr: true
    },
    '/admin': {
      ssr: false, 
    }
  }
})

Additional context

No response

Logs

No response

Mocking definePageMeta for testing

Environment

Reproduction

Running yarn test or npm run test will throw an error: ReferenceError: definePageMeta is not defined

Setup is:

# jest basic dependencies
yarn add --dev @types/jest jest ts-jest jest-transform-stub typescript @babel/preset-env
# vue specific jest helpers
yarn add --dev @vue/vue3-jest @vue/test-utils@next
// ./babel.config.js
module.exports = {
  "presets": ["@babel/env"]
}
// ./jest.config.js
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  moduleFileExtensions: ["js", "jsx", "mjs", "ts", "vue"],
  moduleNameMapper: {
    "^@/(.*)": "<rootDir>/$1",
    "#app": "<rootDir>/node_modules/nuxt3/dist/app/index.mjs"
  },
  transform: {
    '^.+\\.(js|jsx|mjs)$': 'babel-jest',
    '^.+\\.(ts|tsx)$': 'ts-jest',
    ".+\\.(css|scss|png|jpg|svg)$": "jest-transform-stub",
    ".*\\.(vue)$": "@vue/vue3-jest",
  },
  transformIgnorePatterns: [
    "node_modules/(?!(nuxt3|unenv))",
  ],
  setupFiles: [
    "./test-utils/global-test-utils-config.ts"
  ]
};
// ./tsconfig.json
{
  // https://v3.nuxtjs.org/concepts/typescript
  "extends": "./.nuxt/tsconfig.json",
  "compilerOptions": {
    "types": ["@pinia/nuxt", "jest"]
  }
}
// nuxt.config.ts
import { defineNuxtConfig } from "nuxt3";

// https://v3.nuxtjs.org/docs/directory-structure/nuxt.config
export default defineNuxtConfig({
  buildModules: ["@pinia/nuxt"],
  modules: ["@nuxtjs/tailwindcss"],
});
// ./test-utils/global-test-utils-config.ts
import {ref} from "vue";
/** Mock Nuxt's useState to be a simple ref for unit testing. **/
jest.mock("#app", () => ({
    useState: <T>(key: string, init: () => T) => {
        return ref(init())
    }
}))
// ./pages/index.vue
<script setup lang="ts">
definePageMeta({
  middleware: ["auth"],
});
</script>

<template>
  <div>
    <h1>Index</h1>
  </div>
</template>

// ./__test__/pages/index.test.ts
import { mount } from "@vue/test-utils";
import Page from "../../pages/index.vue";

describe("index page", () => {
  it("renders correctly", () => {
    const page = mount(Page);

    expect(page.text()).toContain("Index");
  });
});
// ./package.json
{
  "private": true,
  "scripts": {
    "dev": "nuxi dev",
    "build": "nuxi build",
    "preview": "nuxi preview",
    "start": "node .output/server/index.mjs",
    "test": "jest"
  },
  "devDependencies": {
    "@babel/preset-env": "^7.16.11",
    "@nuxtjs/style-resources": "^1.2.1",
    "@nuxtjs/tailwindcss": "^5.0.0-4",
    "@types/jest": "^27.4.0",
    "@vue/test-utils": "^2.0.0-rc.18",
    "@vue/vue3-jest": "^27.0.0-alpha.4",
    "jest": "^27.5.1",
    "jest-transform-stub": "^2.0.0",
    "nuxt3": "latest",
    "sass": "^1.49.8",
    "sass-loader": "^12.6.0",
    "ts-jest": "^27.1.3",
    "typescript": "^4.5.5"
  },
  "dependencies": {
    "@pinia/nuxt": "^0.1.8",
    "pinia": "^2.0.11"
  }
}

Describe the bug

Hey there,

I followed the steps from this medium article to set up jest for nuxt3.
https://medium.com/@fgoessler/set-up-nuxt3-with-jest-typescript-80aa4d3cfabc

It basically works fine and i can run tests. The problem is, that i don't know how to mock nuxt's definePageMeta for jest. I'm getting the following error while running the test (see Logs).

The medium article i followed is mocking useState. I used useState to test it, and it worked fine if i imported it from #app. For better understanding:

The following won't work with jest:

<script setup lang="ts">
const t = useState("test", () => 1);
</script>

This will work with jest:

<script setup lang="ts">
import { useState } from "#app";
const t = useState("test", () => 1);
</script>

I tried to do the same with definePageMeta but didn't have any success. What am i missing here? Thanks in advance :)

Additional context

No response

Logs

FAIL  __test__/pages/index.test.ts
  index page
    โœ• renders correctly (8 ms)

  โ— index page โ€บ renders correctly

    ReferenceError: definePageMeta is not defined

      1 | <script setup lang="ts">
    > 2 | definePageMeta({
        | ^
      3 |   middleware: ["auth"],
      4 | });
      5 | </script>

      at setup (pages/index.vue:2:1)
      at callWithErrorHandling (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:157:22)
      at setupStatefulComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6977:29)
      at setupComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6933:11)
      at mountComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4855:13)
      at processComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4830:17)
      at patch (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4433:21)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4970:21)
      at ReactiveEffect.run (node_modules/@vue/reactivity/dist/reactivity.cjs.js:171:25)
      at setupRenderEffect (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5089:9)
      at mountComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4872:9)
      at processComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4830:17)
      at patch (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4433:21)
      at render (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5574:13)
      at mount (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:3856:25)
      at Object.app.mount (node_modules/@vue/runtime-dom/dist/runtime-dom.cjs.js:1539:23)
      at mount (node_modules/@vue/test-utils/dist/vue-test-utils.cjs.js:8002:18)
      at Object.<anonymous> (__test__/pages/index.test.ts:6:23)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)

Cannot find name 'useLazyAsyncData'

I'm using Nuxt Bridge with typescript. Calling useLazyAsyncData works fine (it builds without error and everything works) but vscode can't find the function so I have no intellisense.

<script lang="ts" setup>
interface Users {
  data: [{ email: string }];
}

const getUsers = (): Promise<Users> =>
  fetch("https://reqres.in/api/users?page=2")
    .then((res) => res.json())
    .then((res) => res as Users);

const { data } = useLazyAsyncData("users", getUsers);
</script>

according to vscode data has type any because useLazyAsyncData can't be found (it has a red squiggly under it). Can I explicitly import this function from somewhere?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.