Vuetify & Webpack Encore compilation error - vue.js

I created (currently standalone) and API and a VueJs (with Vuetify) App and wanted to combine both using the webpack encore bundle for Symfony.
But when I want to build the frontend app, I get this error when executing yarn run encore dev:
(node:12500) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
at items.forEach.item (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:21:60)
at Set.forEach (<anonymous>)
at Object.getMatches (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:16:9)
at Object.module.exports (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:106:64)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This is my webpack.config.js
const Encore = require('#symfony/webpack-encore');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.cleanupOutputBeforeBuild()
.addEntry('js/main', './assets/js/main.js')
.enableVueLoader()
.enableBuildNotifications(true)
.addPlugin(new VuetifyLoaderPlugin())
;
module.exports = Encore.getWebpackConfig();
Any idea? The standalone app is working fine, I simply moved it to the assets/js folder. I require vuetify-loader ^1.2.2 for this.
And this is my main.js:
import Vue from 'vue'
import App from './App.vue'
import Vuetify from 'vuetify/lib'
import MultiFiltersPlugin from './plugins/MultiFilters'
import 'vuetify/src/stylus/app.styl'
import 'material-design-icons-iconfont/dist/material-design-icons.css'
import 'vuetify/dist/vuetify.min.css'
Vue.use(MultiFiltersPlugin);
Vue.use(Vuetify, {
iconfont: 'md',
});
new Vue({render: h => h(App),}).$mount('#app');

Here's an example webpack.config.js file from this working example that shows how to get Symfony and Vuetify (v.2x) to play nice together:
var Encore = require('#symfony/webpack-encore');
// import vuetify-loader as a plugin here
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin')
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.enableVueLoader() // <-- IMPORTANT: this loads Vue
// NOTE: I put my Vue app in assets/vue which I think is non-standard
// but it allows me to structure my Vue app as I would in a non-Symfony app
.addEntry('app', './assets/vue/main.js')
.splitEntryChunks()
.enableSingleRuntimeChunk()
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
.configureBabel(() => {}, {
useBuiltIns: 'usage',
corejs: 3
})
// add VuetifyLoaderPlugin: THIS loads all of the Vuetify components
.addPlugin(new VuetifyLoaderPlugin())
// enables Sass/SCSS support
.enableSassLoader(options => {
options.implementation = require('sass')
options.fiber = require('fibers')
})
;
module.exports = Encore.getWebpackConfig();
Caveat, I'm not really a symfony developer, but this worked for me. HTH!

Related

Breaking change of loading Vue? between electron 19.1.5 and electron 20.0.0

I used Vue 2.6.14 in my electron app, calling it from main JavaScript script like this:
import Wookmark from 'wookmark/wookmark';
import Vue from 'vue'; // <-- HERE
import {Language} from './model/language';
import Header from '../vue/header.vue';
import VueContextMenu from "vue-context-menu";
import bsn from "bootstrap.native";
Before electron 19.1.5 it worked well, but after electron 20.0.0, this code does not worked.
The code stopped around import Vue from 'vue'; with error Uncaught (in promise) Error: module not found: ./maplist (NOTE: maplist is the name of this script).
What is this breaking change between electron 19 and 20?
How can I avoid it?
Conditions:
electron: 19.1.5 and 20.0.0
Vue: 2.6.14
electron-builder: 23.6.0
vue-loader: 15.9.8
vue-template-compiler: 2.6.14
vue-context-menu: 2.0.6
I don't use any "vue-electron"-ish solutions.
======
Additional info:
With checking this page, I found workaround that adding sandbox: false setting in my main.js
mainWindow = new BrowserWindow({
width: appWidth,
height: appHeight,
webPreferences: {
preload: path.join(__dirname, '../../frontend/api/preload.js'), // eslint-disable-line no-undef
sandbox: false // <- This
}
});
But the defult value of sandbox is true, I believe it is by security reason, so I want to know how to call vue with default sandbox setting, to keep security.

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,
};

Nuxt, VueJS This must be called within a setup function

I've got a project. It's currently available on a certain website. I need to implement some changes. When I download a project from gitlab and run it throws me an error:This must be called within a setup function.
path: .nuxt/composition-api/index.js
const useContext = () => {
const vm = CompositionApi.getCurrentInstance();
if (!vm)
throw new Error("This must be called within a setup function.");
return {
...(vm[globalNuxt] || vm.$options).context,
route: CompositionApi.computed(() => vm.$route),
query: CompositionApi.computed(() => vm.$route.query),
What is wrong?
I need to run the project to make some changes but can't deploy it on my local server.
Update:
useContex is in default.vue
...
setup (_, { isServer, refs }: any) {
// console.info(context)
// const refs = context.refs
const { store } = useContext()
const { scrolllock } = scrollLock(store)
const locationName = computed(() => store.getters.locationName)
const location = computed({
set (val: boolean) {
store.dispatch('setLocationModal', val)
},
get () {
return store.getters.locationModal
}
})
...
cmd output when I'm trying to go the site
[Vue warn]: [vue-composition-api] already installed. Vue.use(VueCompositionAPI) should be called only once.
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:04
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:05
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:24
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>
From my experience, npm can't install #nuxtjs/composition-api older versions, or stuff like that, so I did uninstall its older version and install the new version and it's worked
here is what I've done
rm -rf node_modules && rm -rf package-lock.json && npm uninstall #nuxtjs/composition-api && npm i #nuxtjs/composition-api && npm i
From the look of things, it seems you
You created another plugin for the VueCompositionAPI when it is installed already e.g #nuxtjs/composition-api
I would advise you to remove any other composition-api from your project and stick to the latest version of the official #nuxtjs/composition-api with Vuex v4 for Nuxt 2
In the latest version of #nuxtjs/composition-api, you could use
const store = useStore();
// OR
const { store } = useContext();
NOTE: You have to define the helper functions like const router = useStore() directly inside your setup() function, and not inside your method, to avoid This must be called within a setup function error.
For those that want to use route
To smooth your upgrade to Nuxt 3, it is recommended not to access route, query, from and params from useContext but rather to use the useRoute helper function.
I don't know what happened there. I deleted that repository and cloned it again.
Next up I did this:
npm init
and then
npm run dev
And it works.

getting error when trying to upgrade to vuetify 2.0

Ok so I am trying for the second time to migrate thus far it has been a complete failure it seems that vuetify is not detected, unfortunately I cannot share my full repo since it is work related, but will describe steps and share relevant code.
Project was created with vue-cli 3.3.0 with a vue.config.js file for environment variables.
1) npm uninstall vuetify
2)vue add vuetify
3)npm run serve
my site does not load and I get this error (adding code):
//vue.config.js
module.exports = {
chainWebpack: (config) => {
config.plugin('define')
.tap(([options, ...args]) => {
let env = options['process.env'].VUE_APP_ENV.replace(/"/g,'');
let envMdl = require('./build/' + env.toString() + '.js');
// replace all current by VUE concrente ones to be passed to the app
const processEnv = Object.assign({}, options['process.env'])
Object.keys(envMdl).forEach(function (k) {
processEnv['VUE_APP_' + k] = envMdl[k];
});
const ret = Object.assign({}, options, {'process.env': processEnv});
return [
ret,
...args
]
})
}
}
//vuetify.js
import Vue from 'vue'
import Vuetify from 'vuetify/lib'
Vue.use(Vuetify)
export default new Vuetify({
icons: {
iconfont: 'mdiSvg',
},
})
//main.js
import vuetify from './plugins/vuetify'
...
new Vue({
vuetify,
router,
store,
i18n,
render: h => h(App),
...
Error message (and screenshot): Uncaught TypeError: _lib.default is not a constructor
at eval (vuetify.js?402c:6)
The main problem is that Vuetify v1 works under the Stylus preprocessor, and in v2 it works under the SASS preprocessor, and I personally do not recommend migrating to v2 if it is too advanced and even worse if it has custom Vuetify components.

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>