Adding a plugin to vite - vue.js

I am trying out Vite and using it to develop a Vue app with Prismic Cms. In reading Prismic Doc's I see have to install dependencies
npm install #prismicio/vue #prismicio/client prismic-dom
Doc's then say you have to register it:
To use #prismicio/vue, you must register it in your app entry point, which is most likely ~/src/main.js.
The access token and API options are only necessary if your repo is set to private.
// `~/src/main.js`
import Vue from 'vue'
import App from './App'
import PrismicVue from '#prismicio/vue'
import linkResolver from './link-resolver' // Update this path if necessary
const accessToken = '' // Leave empty if your repo is public
const endpoint = 'https://your-repo-name.cdn.prismic.io/api/v2' // Use your repo name
// Register plugin
Vue.use(PrismicVue, {
endpoint,
apiOptions: { accessToken },
linkResolver
})
In reading Vite doc's I see you add plugins via the vite.config.js file instead of using Vue.use() in main.js. So I created one as follows:
import { defineConfig } from "vite";
import Vue from "#vitejs/plugin-vue";
import PrismicVue from "#prismicio/vue";
import linkResolver from "./link-resolver"; // Update this path if necessary
const accessToken = ""; // Leave empty if your repo is public
const endpoint = "https://*******-****.cdn.prismic.io/api/v2"; // Use your repo name
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
Vue(),
PrismicVue({
endpoint,
apiOptions: { accessToken },
linkResolver,
}),
],
});
However I get error as follows:
failed to load config from C:\Users\akill\Github\shs\vite.config.js
error when starting dev server:
TypeError: (0 , import_vue.default) is not a function at Object.<anonymous> (C:\Users\akill\Github\shs\vite.config.js:53:28)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.require.extensions.<computed> [as .js]
(C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:76005:20)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at loadConfigFromBundledFile (C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:76013:17)
at loadConfigFromFile (C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:75932:32)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! shs#0.0.0 dev: `vite --open`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the shs#0.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
I also notice VS Code is giving me a hint # import of PrismicVue line of
Could not find a declaration file for module '#prismicio/vue'. 'c:/Users/akill/Github/shs/node_modules/#prismicio/vue/dist/prismic-vue.common.js' implicitly has an 'any' type.
I have isolated it to the line "PrismicVue({endpoint,apiOptions: { accessToken }, Etc....})," causing the error. Can someone explain what is the proper way to import this plugin in Vite? Thanks in advance.

vite.config.js's plugins property is intended for Vite plugins, which are for Vite itself (e.g., adding a custom transform for specific file types). That config is not for Vue plugins, which can only be installed in a Vue 3 app with app.use().
To setup Prismic with Vue 3:
Install the following dependencies. The alpha versions of #prismicio/vue and #prismicio/client (3.x and 6.x, respectively) are needed for Vue 3 support.
npm i -S #prismicio/vue#alpha #prismicio/client#alpha prismic-dom
Create a link resolver that returns a route path based on a given Prismic document type. The resolved route path should already be registered in router.js:
const resolver = doc => {
if (doc.isBroken) {
return '/not-found'
}
if (doc.type === 'blog_home') {
return '/blog'
} else if (doc.type === 'post') {
return '/blog/' + doc.uid
}
return '/not-found'
}
export default resolver
In src/main.js, use createPrismic() from #prismic/vue to create the Vue plugin, and pass that along with the link resolver to app.use():
import { createApp } from 'vue'
import { createPrismic } from '#prismicio/vue'
import linkResolver from './prismic/link-resolver'
import App from './App.vue'
import router from './router'
createApp(App)
.use(router)
.use(createPrismic({
endpoint: 'https://blog-demo2.prismic.io/api/v2',
linkResolver,
}))
.mount('#app')
demo

You probably have a mess in your setup / package.json as there is nothing special to do - I bet that you are missing vite-plugin-vue2 and vue-template-compiler.
To get it working, try to create a new project with the following :
vite.config.js:
const { createVuePlugin } = require('vite-plugin-vue2');
module.exports = {
plugins: [
createVuePlugin()
]
};
main.js:
import Vue from 'vue';
import App from './App.vue';
import PrismicVue from "#prismicio/vue";
const accessToken = ""; // Leave empty if your repo is public
const endpoint = "https://*******-****.cdn.prismic.io/api/v2"; // Use your repo name
Vue.use(PrismicVue, {
endpoint: endpoint
});
new Vue({
render: (h) => h(App),
}).$mount('#app');
App.vue:
<template>
<div id="app">
<img
alt="Vue logo"
src="./assets/logo.png"
/>
</div>
</template>
<style>
#app {
text-align: center;
}
</style>
then package.json:
{
"name": "vue2-prismic",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"dependencies": {
"#prismicio/client": "^5.1.0",
"#prismicio/vue": "^2.0.11",
"prismic-dom": "^2.2.6",
"vite-plugin-vue2": "^1.4.0",
"vue": "^2.6.12",
"vue-template-compiler": "^2.6.14"
},
"devDependencies": {
"vite": "^2.0.5"
}
}

Related

Web3js fails to import in Vue3 composition api project

I've created a brand new project with npm init vite bar -- --template vue. I've done an npm install web3 and I can see my package-lock.json includes this package. My node_modules directory also includes the web3 modules.
So then I added this line to main.js:
import { createApp } from 'vue'
import App from './App.vue'
import Web3 from 'web3' <-- This line
createApp(App).mount('#app')
And I get the following error:
I don't understand what is going on here. I'm fairly new to using npm so I'm not super sure what to Google. The errors are coming from node_modules/web3/lib/index.js, node_modules/web3-core/lib/index.js, node_modules/web3-core-requestmanager/lib/index.js, and finally node_modules/util/util.js. I suspect it has to do with one of these:
I'm using Vue 3
I'm using Vue 3 Composition API
I'm using Vue 3 Composition API SFC <script setup> tag (but I imported it in main.js so I don't think it is this one)
web3js is in Typescript and my Vue3 project is not configured for Typescript
But as I am fairly new to JavaScript and Vue and Web3 I am not sure how to focus my Googling on this error. My background is Python, Go, Terraform. Basically the back end of the back end. Front end JavaScript is new to me.
How do I go about resolving this issue?
Option 1: Polyfill Node globals/modules
Polyfilling the Node globals and modules enables the web3 import to run in the browser:
Install the ESBuild plugins that polyfill Node globals/modules:
npm i -D #esbuild-plugins/node-globals-polyfill
npm i -D #esbuild-plugins/node-modules-polyfill
Configure optimizeDeps.esbuildOptions to use these ESBuild plugins.
Configure define to replace global with globalThis (the browser equivalent).
import { defineConfig } from 'vite'
import GlobalsPolyfills from '#esbuild-plugins/node-globals-polyfill'
import NodeModulesPolyfills from '#esbuild-plugins/node-modules-polyfill'
export default defineConfig({
⋮
optimizeDeps: {
esbuildOptions: {
2️⃣
plugins: [
NodeModulesPolyfills(),
GlobalsPolyfills({
process: true,
buffer: true,
}),
],
3️⃣
define: {
global: 'globalThis',
},
},
},
})
demo 1
Note: The polyfills add considerable size to the build output.
Option 2: Use pre-bundled script
web3 distributes a bundled script at web3/dist/web3.min.js, which can run in the browser without any configuration (listed as "pure js"). You could configure a resolve.alias to pull in that file:
import { defineConfig } from 'vite'
export default defineConfig({
⋮
resolve: {
alias: {
web3: 'web3/dist/web3.min.js',
},
// or
alias: [
{
find: 'web3',
replacement: 'web3/dist/web3.min.js',
},
],
},
})
demo 2
Note: This option produces 469.4 KiB smaller output than Option 1.
You can avoid the Uncaught ReferenceError: process is not defined error by adding this in your vite config
export default defineConfig({
// ...
define: {
'process.env': process.env
}
})
I found the best solution.
The problem is because you lose window.process variable, and process exists only on node, not the browser.
So you should inject it to browser when the app loads.
Add this line to your app:
window.process = {
...window.process,
};

Runtime Error integrating a component lib that uses #vue/composition-api: 'You must use this function within the "setup()" method'

Any help with the following problem would be greatly appreciated!
Situation:
My project contains two packages:
child-component-lib
contains a single view About.vue written in composition-API-style (with vue2 helper libraries #vue/composition-api and vuex-composition-helpers)
exports a single RouteConfig
build as a lib
views/About.vue (child)
<template>
<div class="about">
<h1>This is an about page (as component lib)</h1>
</div>
</template>
<script>
import { defineComponent } from "#vue/composition-api";
import { createNamespacedHelpers } from "vuex-composition-helpers";
export default defineComponent({
components: {},
setup(_, { root }) {
const { useGetters, useActions } = createNamespacedHelpers("account"); // error thrown here!
}
});
</script>
router/index.ts (child)
export const routes: Array<RouteConfig> = [{
path: "/",
name: "About",
component: () => import(/* webpackChunkName: "about" */ "../views/About.vue")
}];
lib.ts (child)
export const routes = require("#/router").routes;
package.json (child)
"scripts": {
"build": "vue-cli-service build --target lib --name child-component-lib src/lib.ts"
...
parent-app
imports the route from child-component-lib into its router
contains a simple view that displays one line of text and a <router-view />
package.json (parent)
"dependencies": {
"#tholst/child-component-lib": "file:../child-component-lib",
router/index.ts (parent)
import { routes as childComponentRoutes } from "#tholst/child-component-lib";
const routes: Array<RouteConfig> = [...childComponentRoutes];
const router = new VueRouter({routes});
export default router;
App.vue (parent)
<template>
<div id="app">
<Home />
<router-view />
</div>
</template>
<script>
import { defineComponent } from "#vue/composition-api";
import Home from "#/views/Home.vue";
export default defineComponent({
components: {
Home
},
setup(_, { root }) {
...
}
});
</script>
Expected behavior
It works without problems.
Actual behavior
I see an error output in the console. [Vue warn]: Error in data(): "Error: You must use this function within the "setup()" method, or insert the store as first argument." The error message is misleading, because the error is actually thrown inside setup() method. It can be traced back to getCurrentInstance() returning undefined (inside #vue/composition-api).
Investigation:
It turns out that the error disappears when I include the same About.vue in the parent-app itself (just switch the route, to try it out), i.e., it works when we avoid the import from the built library.
So it looks like it's a problem with the build setup
(one of vue.config.js, webpack, babel, typescript, ...)
Reproduce the error:
1. Clone, install, run
git clone git#github.com:tholst/vue-composition-api-comp-lib.git && cd vue-composition-api-comp-lib/child-component-lib && npm install && npm run build && cd ../parent-app/ && npm install && npm run serve
or one by one
git clone git#github.com:tholst/vue-composition-api-comp-lib.git
cd vue-composition-api-comp-lib/child-component-lib
npm install
npm run build
cd ../parent-app/
npm install
npm run serve
2. Open Browser
Go to http://localhost:8080/
3. Open Dev Tools to See Error
[Vue warn]: Error in data(): "Error: You must use this function within the "setup()" method, or insert the store as first argument."
found in
---> <Anonymous>
<App> at src/App.vue
<Root>
Error Screenshot
Environment Info:
Node: 14.2.0
npm: 6.14.8
Chrome: 86.0.4240.198
npmPackages:
#vue/babel-sugar-composition-api-inject-h: 1.2.1
#vue/babel-sugar-composition-api-render-instance: 1.2.4
...
#vue/cli-overlay: 4.5.8
#vue/cli-plugin-babel: 4.5.8
#vue/cli-plugin-router: 4.5.8
#vue/cli-plugin-typescript: 4.5.8
#vue/cli-plugin-vuex:4.5.8
#vue/cli-service: 4.5.8
#vue/cli-shared-utils: 4.5.8
#vue/component-compiler-utils: 3.2.0
#vue/composition-api: 1.0.0-beta.19
#vue/preload-webpack-plugin: 1.1.2
typescript: 3.9.7
vue: 2.6.12
vue-loader: 15.9.5 (16.0.0-rc.1)
vue-router: 3.4.9
vue-template-compiler: 2.6.12
vue-template-es2015-compiler: 1.9.1
vuex: 3.5.1
vuex-composition-helpers: 1.0.21
npmGlobalPackages:
#vue/cli: 4.5.8
I finally understood what the problems were. First, there was the actual problem. Second, there was a problem in the local development setup that made solutions to the actual problem look like they were not working.
The Actual Problem + Solution
The child-component-lib was bundling their own versions of the npm packages #vue/composition-api and vuex-composition-helpers. This had the following effect: When I was running the parent-app there were actually two instances of those libraries and the vue component from the child-component-lib was accessing the wrong object that had not been properly initialized.
The solution was to prevent the bundling of those libraries in the child-component-lib, by
making them devDependencies and peerDependencies.
instructing webpack not to bundle them on npm run build.
package.json
"dependencies": {
...
},
"devDependencies": {
"#vue/composition-api": "^1.0.0-beta.19",
"vuex-composition-helpers": "^1.0.21",
...
},
"peerDependencies": {
"#vue/composition-api": "^1.0.0-beta.19",
"vuex-composition-helpers": "^1.0.21"
},
vue.config.js
configureWebpack: {
externals: {
"#vue/composition-api": "#vue/composition-api",
"vuex-composition-helpers": "vuex-composition-helpers"
},
...
}
The Tricky Problem that Made Things Difficult
I was trying to fix this problem locally, without actually publishing the package. And it seemed to work, because I was seeing the same problem locally that I also saw in the published packages.
I did local development by directly linking the parent-app and child-component-libs. I tried both
a direct folder dependency
package.json
"dependencies": {
"#tholst/child-component-lib": "file:../child-component-lib",
},
npm link
cd child-component-lib
npm link
cd ../parent-app
npm link #tholst/child-component-lib
Both approaches have the effect that they actually import (=symlink to) the child-component-lib's folder with all files and folders (instead of only the files that would be published in the npm package).
And that meant the following: Even though I had excluded the two composition-API libs from the bundle and made them dev/peer dependencies (see solution to actual problem), they were still installed and present in the child-component-lib's node_modules. And that node_modules folder was symlinked into the parent-app package. And in this way the child-component-lib still had access to their own copy of the libraries that we wanted to exclude from the build (see actual problem). And I was still seeing the error as before.
And this way my local development approach obscured the fact that the solution to the actual problem was actually working.

Invalid or Unexpected Token - Vue.js, after implementing vue-gallery (Blueimp Gallery for vue)

I'm attempting to implement vue-gallery in vue.js, which I built using nuxt.js.
I've followed various examples and github issue answers, to no avail. I turn here because I've exhausted my current problem solving and googling capabilities:)
================== UPDATE
New error message is:
warning in ./plugins/vue-gallery.js
"export 'default' (imported as 'VueGallery') was not found in 'vue-gallery'
I updated nuxt.config.js to look like this:
build: {
/*
** add vue-gallery to transpile process
*/
transpile: ['vue-gallery'],
/*
** Use autoprefixer
*/
postcss: [
require('autoprefixer')
],
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
And I tried updating vue-gallery.js to see if I could fix the export default issue, to this:
import Vue from 'vue'
import VueGallery from 'vue-gallery'
export default function vuegallery() {
if (process.browser) {
// VueGallery = require('vue-gallery')
Vue.use(VueGallery, {name: 'vue-gallery'})
}
console.log('plugin vue-gallery is locked and loaded')
}
===================
The code repo is available at:
https://bitbucket.org/earleymw/front-end-dev-test-1/src/master/
The error in CLI is
✖ error /Users/mikeearley/code/front-end-dev-test-1/rogue-challenge/node_modules/blueimp-gallery/css/blueimp-gallery.min.css:1
(function (exports, require, module, __filename, __dirname) { #charset "UTF-8";.blueimp-gallery,.blueimp-gallery>.slides>.slide>.slide-content{position:absolute;top:0;right:0;bottom:0;left:0;-moz-backface-visibility:hidden}.blueimp-gallery>.slides>.slide>.slide-content{margin:auto;width:auto;height:auto;max-width:100%;max-height:100%;opacity:1}.blueimp-gallery{position:fixed;z-index:999999;overflow:hidden;background:#000;background:rgba(0,0,0,.9);opacity:0;display:none;direction:ltr;-ms-touch-action:none;touch-action:none}.blueimp-gallery-carousel{position:relative;z-index:auto;margin:1em auto;padding-bottom:56.25%;box-shadow:0 0 10px #000;-ms-touch-action:pan-y;touch-action:pan-y}.blueimp-gallery-display{display:block;opacity:1}.blueimp-gallery>.slides{position:relative;height:100%;overflow:hidden}.blueimp-gallery-carousel>.slides{position:absolute}.blueimp-gallery>.slides>.slide{position:
SyntaxError: Invalid or unexpected token
The error in the browser is:
SyntaxError
Invalid or unexpected token
module.js
Missing stack framesJS
Module.require#579:17
vm.js:80:10
createScript
vm.js:139:10
Object.runInThisContext
module.js:599:28
Module._compile
module.js:646:10
Module._extensions..js
module.js:554:32
Module.load
module.js:497:12
tryModuleLoad
module.js:489:3
Module._load
module.js:579:17
Module.require
internal/module.js:11:18
require
module.js:635:30
Module._compile
module.js:646:10
Module._extensions..js
module.js:554:32
Module.load
module.js:497:12
tryModuleLoad
module.js:489:3
Module._load
Currently, I have a '~/plugins/vue-gallery.js' file containing:
import Vue from 'vue'
import VueGallery from 'vue-gallery'
if (process.browser) {
// VueGallery = require('vue-gallery')
Vue.use(VueGallery, {name: 'vue-gallery'})
}
console.log('plugin vue-gallery is locked and loaded')
And in 'nuxt.config.js':
/*
** plugins
*/
plugins: [{ src: '~/plugins/vue-gallery.js', ssr: false }],
And in index.vue:
I have tested locally and found that there no such error happens. You dont need to add it to transpile.
And you are import vue gallery wrong. Vue.use is for vue plugins, while VueGallery is just a component, not a plugin. So your code should be like this:
import Vue from 'vue'
import VueGallery from 'vue-gallery'
Vue.component('vue-gallery', VueGallery)
And as you can see you dont need check for browser, because you already set ssr: false for this plugin in nuxt config.

Angular5 / Webworker - Tried to find bootstrap code, but could not

I try to follow all these tutorials about webworker, but no one works. This is one of them: https://blog.angularindepth.com/angular-with-web-workers-step-by-step-dc11d5872135
I follow step by step but after I run npm start I get a
ERROR in Error: Tried to find bootstrap code, but could not. Specify either statically analyzable bootstrap code or pass in an entryModule to the plugins options.
at Object.resolveEntryModuleFromMain (D:\PROJECTS_TIQ\w3\worky\node_modules\#ngtools\webpack\src\entry_resolver.js:121:15)
at Promise.resolve.then.then (D:\PROJECTS_TIQ\w3\worky\node_modules\#ngtools\webpack\src\angular_compiler_plugin.js:240:54)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
at Function.Module.runMain (module.js:678:11)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
this is my main.ts .. I think the problem is here, but what..?
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { bootstrapWorkerUi } from '#angular/platform-webworker';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapWorkerUi('webworker.bunde.js')
.catch(err => console.log(err));
also.. this tutorial talks about some kind of AotPlugin that should be in the webpack.config.js .. but when I do npm eject there is no AotPlugin imported in the confg(?)

How to use Graphql in NuxtJs

So I want to implement GraphQL into NuxtJs.
Now I need to have a provider into the root element, but NuxtJs doesn't give me this option.
How would I inject the apolloProvider into the root Vue element?
What I'm trying to accomplish:
https://github.com/Akryum/vue-apollo
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
new Vue({
el: '#app',
apolloProvider,
render: h => h(App),
})
What I've tried:
Creating a plugin: /plugins/graphql.js:
import Vue from 'vue'
import { ApolloClient, createBatchingNetworkInterface } from 'apollo-client'
import VueApollo from 'vue-apollo'
// Create the apollo client
const apolloClient = new ApolloClient({
networkInterface: createBatchingNetworkInterface({
uri: 'http://localhost:3000/graphql'
}),
connectToDevTools: true
})
// Install the vue plugin
Vue.use(VueApollo)
const apolloProvider = new VueApollo({
defaultClient: apolloClient
})
export default apolloProvider
Importing the apolloProvider in .nuxt/index.js:
...
import apolloProvider from '../plugins/graphql'
...
let app = {
router,
store,
apolloProvider,
_nuxt: {
defaultTransition: defaultTransition,
transitions: [ defaultTransition ],
...
Unfortunately this provides me with 2 problems; each time the server restarts, my code in the .nuxt directory is wiped. Besides that it gives me the following error:
TypeError: Cannot set property '__APOLLO_CLIENT__' of undefined
at new ApolloClient (/current/project-nuxt/node_modules/apollo-client/src/ApolloClient.js:112:37)
at Object.<anonymous> (plugins/graphql.js:6:21)
at __webpack_require__ (webpack:/webpack/bootstrap 8a1e0085b0ebc1e03bd0:25:0)
at Object.module.exports.__webpack_exports__.a (server-bundle.js:1060:76)
at __webpack_require__ (webpack:/webpack/bootstrap 8a1e0085b0ebc1e03bd0:25:0)
at Object.<anonymous> (server-bundle.js:1401:65)
at __webpack_require__ (webpack:/webpack/bootstrap 8a1e0085b0ebc1e03bd0:25:0)
at server-bundle.js:95:18
at Object.<anonymous> (server-bundle.js:98:10)
at evaluateModule (/current/project-nuxt/node_modules/vue-server-renderer/build.js:5820:21)
at /current/project-nuxt/node_modules/vue-server-renderer/build.js:5878:18
at /current/project-nuxt/node_modules/vue-server-renderer/build.js:5870:14
at Nuxt.renderToString (/current/project-nuxt/node_modules/vue-server-renderer/build.js:6022:9)
at P (/current/ducklease-nuxt/node_modules/pify/index.js:49:6)
at Nuxt.<anonymous> (/current/project-nuxt/node_modules/pify/index.js:11:9)
at Nuxt.ret [as renderToString] (/current/project-nuxt/node_modules/pify/index.js:72:32)
at Nuxt._callee2$ (/current/project-nuxt/node_modules/nuxt/dist/webpack:/lib/render.js:120:24)
at tryCatch (/current/project-nuxt/node_modules/regenerator-runtime/runtime.js:65:40)
at GeneratorFunctionPrototype.invoke [as _invoke] (/current/project-nuxt/node_modules/regenerator-runtime/runtime.js:303:22)
at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/current/project-nuxt/node_modules/regenerator-runtime/runtime.js:117:21)
at step (/current/project-nuxt/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
at /current/project-nuxt/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13
Maybe a little late, but there is #nuxtjs/apollo plugin.
I've used this for my blog, using Nuxt 1.0, I'm still doing some testing on Nuxt2, but its giving me issues.. guess I'll stick with V1 for the moment.
.nuxt folder restarts every time you rebuild the project, so it would not be the ideal place to inject your module.
Nuxt has nuxt.config.js where you can add your modules to its module array.
they are imported at runtime so make sure they are already transpiled (eg. all the es6 conversions are taken care off)
better description is available in the docs
#nuxtjs/apollo seems like a good option, however if you want to write your own graphql module, this is the way
I'm using [nuxt-apollo][1] "nuxt": "^2.10.2" without issues so far.
npm i #nuxtjs/apollo &&
npm install --save #nuxtjs/apollo
# if you are using *.gql or *.graphql files add graphql-tag to your dependencies
npm install --save graphql-tag
1.Youll need to set up your config as you've stated above,
In nuxt.config.js
export default {
...
modules: ['#nuxtjs/apollo'],
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://api.graph.cool/simple/v1/cj1dqiyvqqnmj0113yuqamkuu' //link to your graphql backend.
}
}
}
}
Make your query
in gql/allCars.gql
{
allCars {
id
make
model
year
}
}
use graphql in your component
in pages /index.vue
<script>
import allCars from '~/apollo/queries/allCars'
export default {
apollo: {
allCars: {
prefetch: true,
query: allCars
}
},
head: {
title: 'Cars with Apollo'
}
}
</script>