Giter Site home page Giter Site logo

dword-design / nuxt-route-meta Goto Github PK

View Code? Open in Web Editor NEW
43.0 2.0 4.0 2.64 MB

Adds Nuxt page data to route meta at build time. Also supports TypeScript.

License: Other

JavaScript 99.56% Shell 0.44%
nuxt nuxtjs nuxt-module nuxtjs-module router vue-router meta-data pages frontend javascript

nuxt-route-meta's Introduction

nuxt-route-meta

npm version Linux macOS Windows compatible Build status Coverage status Dependency status Renovate enabled
Open in Gitpod Buy Me a Coffee PayPal Patreon

Adds Nuxt page data to route meta at build time. Also supports TypeScript.

Nuxt pages have a meta property that allows to define meta data. These can be accessed in middlewares via route.meta at runtime. What does not work however is to access the meta data at build time in the routes object itself. This is needed when postprocessing routes via extendRoutes or the @nuxtjs/sitemap module. This module fills this gap by parsing the page files, extracting the meta data, and writing them to the meta field of each route corresponding to the page.

ℹ️ Note that this module can only extract static data from the pages at build time. It will not work with dynamic data depending on this. In case you have an idea how to improve that, feel free to open up an issue or pull request.

Compatibility

nuxt-route-meta Nuxt
<= 5 2
>= 6 3

Install

# npm
$ npx nuxi module add nuxt-route-meta

# Yarn
$ yarn nuxi module add nuxt-route-meta

Usage

Add the module to your nuxt.config.js:

export default {
  modules: [
    'nuxt-route-meta',
  ]
}

Add some properties to your pages:

<template>
  <div>Hello world</div>
</template>
<script>
export default {
  auth: true,
  meta: {
    theme: 'water',
  },
}
</script>

That's it! Now you can access the meta data in route.meta from anywhere as you know it from vue-router. The module takes all properties that all properties that are not functions, and the meta property itself is merged into the result. So route.meta from the example above is { auth: true, theme: 'water' }.

Here is an example to use it inside nuxt.hook('pages:extend') in a module:

export default defineNuxtModule((options, nuxt) =>
  nuxt.hook('pages:extend', routes =>
    for (const route of routes) {
      if (route.meta.auth) {
        // do something with auth routes
      }
    }
  )
)

Composition API

<script setup>
definePageMeta({
  auth: true,
})
</script>

TypeScript

The module has built-in support for TypeScript.

<script lang="ts">
export default defineComponent({
  auth: true,
  meta: {
    theme: 'water',
  },
})
</script>

Contribute

Are you missing something or want to contribute? Feel free to file an issue or a pull request! ⚙️

Support

Hey, I am Sebastian Landwehr, a freelance web developer, and I love developing web apps and open source packages. If you want to support me so that I can keep packages up to date and build more helpful tools, you can donate here:

Buy Me a Coffee  If you want to send me a one time donation. The coffee is pretty good 😊.
PayPal  Also for one time donations if you like PayPal.
Patreon  Here you can support me regularly, which is great so I can steadily work on projects.

Thanks a lot for your support! ❤️

See also

  • nuxt-mail: Adds email sending capability to a Nuxt.js app. Adds a server route, an injected variable, and uses nodemailer to send emails.
  • nuxt-modernizr: Adds a Modernizr build to your Nuxt.js app.
  • nuxt-mermaid-string: Embed a Mermaid diagram in a Nuxt.js app by providing its diagram string.
  • nuxt-content-git: Additional module for @nuxt/content that replaces or adds createdAt and updatedAt dates based on the git history.
  • nuxt-babel-runtime: Nuxt CLI that supports babel. Inspired by @nuxt/typescript-runtime.

License

MIT License © Sebastian Landwehr

nuxt-route-meta's People

Contributors

actions-user avatar dword-design avatar frsgit avatar github-actions[bot] avatar renovate-bot avatar renovate[bot] avatar semantic-release-bot avatar test123456789012345 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

Watchers

 avatar  avatar

nuxt-route-meta's Issues

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: Cannot find preset's package (github>whitesource/merge-confidence:beta)

Meta is not parsed when page component uses mixins

Hi, I'm using class decorators in SFCs. I found a bug in the parsing algorithm. It only accepts page components which extend Vue directly. The parsing fails to find meta when the component uses mixins:

// pages/index.vue

import {Component, mixins} from 'nuxt-property-decorator';
import SomeMixin from '@/mixins/SomeMixin';

@Component({})
export default PageComponent extends mixins(SomeMixin) {
  meta = {foo: 'bar'};
}

May I suggest parsing the @Component decorator options instead like so?: (only if the typescript AST parser allows it)

@Component({meta: {foo: 'bar'}})

Incompatible with nuxt-property-decorator

Getting this error after enabling this plugin:

Support for the experimental syntax 'decorators-legacy' isn't currently enabled (4:1):                                                                                          08:32:53  

  2 | import { Component, Vue } from 'nuxt-property-decorator';
  3 | 
> 4 | @Component({
    | ^
  5 |   components: {}
  6 | })

My guess is that because the underlying projects used by nuxt-property-decorator are doing some heavy Babel stuff to make things work that when you are using Babel to traverse the ingested component for your purposes that something is conflicting here.

Not sure this is something you even want to take a look at as the property decorator stuff is not used by a lot of folks, but thought I would mention it.

'meta' of undefined

Hi everyone;

I have a problem with this plugin when i build my site.

Error : Cannot read property 'meta' of undefined

I have two solution :
First: add object "meta: {}" in all pages (It's so bad)
Second: Into the lib just change the line 139: "...data.meta" by "...data?.meta"

I while create a pull request for this bug.

Thanks :)

npm install error

nuxt: 2.15.8
node: 16.0.0
npm: 7.10.0

$ npm install nuxt-route-meta
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! Found: [email protected]
npm ERR! node_modules/typescript
npm ERR!   peer typescript@">= 2.7" from [email protected]
npm ERR!   node_modules/fork-ts-checker-webpack-plugin
npm ERR!     fork-ts-checker-webpack-plugin@"^6.1.1" from @nuxt/[email protected]
npm ERR!     node_modules/@nuxt/typescript-build
npm ERR!       dev @nuxt/typescript-build@"^2.1.0" from the root project
npm ERR!   peerOptional typescript@">=4.4.4" from [email protected]
npm ERR!   node_modules/pinia
npm ERR!     peer pinia@">=2.0.14" from @pinia/[email protected]
npm ERR!     node_modules/@pinia/nuxt
npm ERR!       @pinia/nuxt@"^0.1.9" from the root project
npm ERR!     pinia@"^2.0.14" from the root project
npm ERR!   3 more (ts-jest, ts-loader, tsutils)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! nuxt-route-meta@"*" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/typescript
npm ERR!   peer typescript@"~4.2" from [email protected]
npm ERR!   node_modules/nuxt-route-meta
npm ERR!     nuxt-route-meta@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\username\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\username\AppData\Local\npm-cache\_logs\2022-06-28T09_03_54_488Z-debug.log

npm install nuxt-route-meta --legacy-peer-deps but

 ERROR  Cannot find module 'typescript'                                                           17:27:45
Require stack:
- C:\Users\username\Documents\apps\project\node_modules\nuxt-route-meta\dist\index.js 
- C:\Users\username\Documents\apps\project\node_modules\@nuxt\core\dist\core.js       

  Require stack:
  - node_modules\nuxt-route-meta\dist\index.js
  - node_modules\@nuxt\core\dist\core.js
  at Function.Module._resolveFilename (node:internal/modules/cjs/loader:940:15)
  at Function.Module._load (node:internal/modules/cjs/loader:773:27)
  at Module.require (node:internal/modules/cjs/loader:1012:19)
  at require (node:internal/modules/cjs/helpers:93:18)
  at extractMeta (node_modules\nuxt-route-meta\dist\index.js:68:20)
  at Object.parseRoutes (node_modules\nuxt-route-meta\dist\index.js:149:57)
  at next (node_modules\@nuxt\utils\dist\utils.js:659:27)
  at Object.extendRoutes (node_modules\@nuxt\utils\dist\utils.js:674:12)
  at Builder.resolveRoutes (node_modules\@nuxt\builder\dist\builder.js:546:56)
  at async Promise.all (index 1)
  at async Builder.generateRoutesAndFiles (node_modules\@nuxt\builder\dist\builder.js:375:5)
  at async Builder.build (node_modules\@nuxt\builder\dist\builder.js:319:5)
  at async Object._buildDev (node_modules\@nuxt\cli\dist\cli-dev.js:107:5)
  at async Object.startDev (node_modules\@nuxt\cli\dist\cli-dev.js:65:7)
  at async Object.run (node_modules\@nuxt\cli\dist\cli-dev.js:52:5)
  at async NuxtCommand.run (node_modules\@nuxt\cli\dist\cli-index.js:413:7)

not working code

In my setup value.value not exists

  let data = {}
  if (Component.script?.content) {
    const ast = babel.parseSync(Component.script.content, { filename })
    traverse(ast, {
      ExportDefaultDeclaration: path => {
        data =
          path.node.declaration.properties
          |> filter('key.name')
          |> keyBy('key.name')
          |> pick(options.properties)
          //--|> mapValues('value.value')
          //++
          |> mapValues('value.properties')
      },
    })
  }
  if ('meta' in data) {
    Object.assign(data, data.meta)
    delete data.meta
    //++
    data = 
        data
        |> keyBy('key.name')
        |> mapValues('value.value')
  }

works for meta with no inner hierarchy

Add @nuxt/babel-preset-app dependency

Without this dependency it will throw an error when trying to start

Show error
 ERROR  Cannot start nuxt:  Cannot find module '@nuxt/babel-preset-app'                                                                                                                           14:10:29  
Require stack:
- C:\wamp64\www\[project-name]\node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\files\configuration.js
- C:\wamp64\www\[project-name]\node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\files\index.js
- C:\wamp64\www\[project-name]\node_modules\nuxt-route-meta\node_modules\@babel\core\lib\index.js
- C:\wamp64\www\[project-name]\node_modules\nuxt-route-meta\dist\index.js
- C:\wamp64\www\[project-name]\node_modules\@nuxt\core-edge\dist\core.js

Require stack:
- node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\files\configuration.js
- node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\files\index.js
- node_modules\nuxt-route-meta\node_modules\@babel\core\lib\index.js
- node_modules\nuxt-route-meta\dist\index.js
- node_modules\@nuxt\core-edge\dist\core.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at resolve (node:internal/modules/cjs/helpers:108:19)
at loadConfig (node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\files\configuration.js:172:5)
at loadConfig.next (<anonymous>)
at mergeExtendsChain (node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\config-chain.js:387:45)
at mergeExtendsChain.next (<anonymous>)
at node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\config-chain.js:373:20
at Generator.next (<anonymous>)
at buildRootChain (node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\config-chain.js:71:36)
at buildRootChain.next (<anonymous>)
at loadPrivatePartialConfig (node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\partial.js:103:62)
at loadPrivatePartialConfig.next (<anonymous>)
at loadFullConfig (node_modules\nuxt-route-meta\node_modules\@babel\core\lib\config\full.js:57:46)
at loadFullConfig.next (<anonymous>)
at Object.parse (node_modules\nuxt-route-meta\node_modules\@babel\core\lib\parse.js:25:45)
at parse.next (<anonymous>)

As a workaround you can install this package manually and the error will be resolved.

My guess is this package got removed from @babel/core or @babel/traverse dependency's.

Only works if put as last module

I don't know if it's only on my project or in general. But while using nuxt-route-meta in conjunction with @nuxtjs/composition-api, by calling useRoute in SSR I noticed that it only works if put as last module. Don't have time now to try to reproduce. Is there any reason it could work only as last module?

Values set as false disappear

When setting one of the metadata fields to false, they disappear completely from the $route.meta .

File test.vue:

<template>
<code>
isTrue: {{ this.$route.meta.isTrue }}
isFalse: {{ this.$route.meta.isFalse }}
isOther: {{ this.$route.meta.isOther }}
isAlsoTrue: {{ this.$route.meta.isAlsoTrue }}
isAlsoFalse: {{ this.$route.meta.isAlsoFalse }}
</code>
</template>

<script>
export default {
  isTrue: true,
  isFalse: false,
  isOther: 'other',
  meta: {
    isAlsoTrue: true,
    isAlsoFalse: false,
  },
}
</script>

<style scoped>
code {  white-space: pre-wrap; }
</style>

Output:

  isTrue: true
  isFalse: 
  isOther: other
  isAlsoTrue: true
  isAlsoFalse: 

(I'm using v2.0.6 and nuxt v2.15.3.)

remove direct git dependencies

At the moment it's not working with all setups since the package requires git to be installed on the machine (docker)

Some setups need to apply some changes to the deploy pipelines. Not always it's a good idea to make changes in Kubernates because of one npm package (even if it's a very good one 😁🙄😉)

error example:

npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno -2
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t ssh://[email protected]/dword-design/dedent.git
npm ERR! enoent 
npm ERR! enoent 
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

Is it possible to remove direct git dependencies?

Route meta is doesn't work in nested routes

Hello, I have a problem with route meta in nested routes, when I use route meta is doesn't work. I don't know what's wrong someone can help me?

My Pages Folder Structure;

-store
---basket
-----index.vue (meta doesn't work)
---category
-----_category
-------index.vue (meta doesn't work)
---index.vue (meta doesn't work)
-store.vue (meta works) (have only nuxt-child and asyncData functions)

Vue packages version mismatch

Hi :)

After add this package to my project i go this error:

Vue packages version mismatch:

- [email protected] (.../myproject/node_modules/vue/dist/vue.runtime.common.js)
- [email protected] (.../myproject/node_modules/nuxt-route-meta/node_modules/vue-template-compiler/package.json)

Does anyone know why ?

Cannot read property 'type' of undefined

After installing and adding 'nuxt-route-meta', to my nuxt.config.js, i cannot build my application anymore.

Running npm run dev fails and says Cannot read property 'type' of undefined

complete error:

ERROR Cannot read property 'type' of undefined

at toJs (node_modules\ast-to-literal\index.js:6:33)
at node_modules\ast-to-literal\index.js:37:19
at Array.reduce (<anonymous>)
at computeProps (node_modules\ast-to-literal\index.js:30:16)
at toJs (node_modules\ast-to-literal\index.js:15:10)
at ExportDefaultDeclaration (node_modules\nuxt-route-meta\dist\index.js:43:92)
at NodePath._call (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\path\context.js:55:20)
at NodePath.call (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\path\context.js:42:17)
at NodePath.visit (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\path\context.js:92:31)
at TraversalContext.visitQueue (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\context.js:116:16)
at TraversalContext.visitMultiple (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\context.js:80:17)
at TraversalContext.visit (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\context.js:142:19)
at Function.traverse.node (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\index.js:82:17)
at NodePath.visit (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\path\context.js:99:18)
at TraversalContext.visitQueue (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\context.js:116:16)
at TraversalContext.visitSingle (node_modules\nuxt-route-meta\node_modules\@babel\traverse\lib\context.js:85:19)

Route meta remains empty with head() vs head{}

I'm not 100% whether this was mentioned in one of the other issues.

Given my page files structure

head() {
    return {
      title: this.title,
      meta: [
        {
          breadcrumb: this.title,
          hid: this.title,
          name: this.title,
          content: `This page contains ${this.title} content`,
        },
      ],
    }
  },
  data() {
    return {
      title: 'Some title',
    }
  },

After installing and adding to nuxt.config.js like so

  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/firebase',
    'nuxt-route-meta',
  ],

Calling meta in my breadcrumb component like so results in an empty object:

console.log('Meta data is', this.$route.matched[i].meta)

image

Am I missing something? Could this be related to the difference between head as an object and head as a function? Given that I depend on the data() to be returned?

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.