Laravel and vue: require is not defined - laravel

In Laravel version 6 the follwing error happens with vue in the console:
app.js:24703 Uncaught ReferenceError: require is not defined
at app.js:24703
the error points to:
require('./bootstrap');
Webpack.mix.js:
mix.scripts([
'resources/js/jquery-3.4.1.js',
'resources/js/bootstrap.min.js',
'resources/js/toastr.js',
'resources/js/vue.js',
'resources/js/axios.js',
'resources/js/app.js'
], 'public/js/app.js')
.styles([
'resources/css/bootstrap.min.css',
'resources/css/toastr.css'
], 'public/css/app.css');
It works fine VUEJS for me but it doesn’t allow me to add components
Also another thing that I notice is that this error disables me vue devtools.
The code is newly installed, both the Laravel and Vue project and if I create a new project I get the same error.
require('./bootstrap');
window.Vue = require('vue');
Vue.component('message', require('./components/message.vue').default);
const app = new Vue({
el: '#app',
data:{
message: ''
},
methods:{
send(){
if(this.message.length !=0){
console.log(this.message);
}
}
}
});
What am I doing wrong?

It sounds like, somehow, the file is given to the browser hasn't been compiled.
You need to change the configuration Webpack.mix.js
You can try change mix.scripts([]) on mix.js([]) and add .vue().
It helped me.
mix.js([
'resources/js/jquery-3.4.1.js',
'resources/js/bootstrap.min.js',
'resources/js/toastr.js',
'resources/js/vue.js',
'resources/js/axios.js',
'resources/js/app.js'
], 'public/js/app.js') .vue();

Related

Laravel Jetstream Vue mixin route

In a new Laravel project created by the installer with the Jetstream option resources/js/app.js has a line that reads:
Vue.mixin({ methods: { route } });
PHPStorm reports that route is an unresolved variable or type. This happens, PHPStorm can be wrong. In a newly created application this does not cause an error.
However, when I upgraded an existing project to Laravel 8.10.0 and installed Jetstream via composer this does cause and issue. When running this npm run dev does not error, but the browser will report app.js:44258 Uncaught ReferenceError: route is not defined.
I can find no difference in app.js or bootstrap.js that would cause this. Where does this get imported or included so that I can check if it was done correctly in my upgrade?
The newly created app and the update both create a Blade template that includes the #routes directive. As I was comparing existing files I did not notice this difference.
This can be corrected by including the #routes directive in your blade template prior to the main scripts being loaded, as documented in the installation guide for ziggy.
With the suggestion of ToothlessRebel, this is how I solved my error :
Step 1 command line :
composer require tightenco/ziggy
npm install ziggy-js
php artisan ziggy:generate "resources/js/ziggy.js"
step 2 : modify webpack.mix.js :
mix.js('resources/js/app.js', 'public/js')
...
.webpackConfig(require('./webpack.config'));
And in ./webpack.config :
const path = require('path');
module.exports = {
resolve: {
alias: {
'#': path.resolve('resources/js'),
ziggy: path.resolve('vendor/tightenco/ziggy/src/js/route.js'),
},
},
};
Step 3 : app.js :
import route from 'ziggy';
import {
Ziggy
} from './ziggy';
...
Vue.mixin({
methods: {
route: (name, params, absolute) => route(name, params, absolute, Ziggy),
},
});
...
new Vue({
el: "#app",
render: (h) =>
h(InertiaApp, {
props: {
initialPage: JSON.parse(app.dataset.page),
resolveComponent: (name) => require(`./Pages/${name}`).default,
},
}),
});
and finally a command : npm run dev
So, my dashboard and all mixin/ziggy routes are working...
Not anymore my vue-router routes ... I guess I have a conflit I have to resolve, but it's an other problem

Is there anyone who is familiar with Laravel mix.webpackConfig ? After installing vuetify , something went wrong

I am using Laravel. the Frontside is developed by Blade and vue.
After Installing "vuetify". The other component which I have been using happened an error.
I don't know what is going on. the component doesn't be shown in the div.
when "const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');" is removed from mix.webpackconfig, the error from Calendar disappeared.
Is that related to installing "vuetifty"?
ERROR
[Vue warn]: Error in render: "TypeError: Cannot read property 'lang' of undefined"
found in
---> <VCalendarMonthly>
<VCalendar>
<ACalendar> at resources/js/components/ACalendar.vue
<Root>
app.js
Code
window.Vue = require('vue');
Vue.use(require('v-calendar'));
Vue.component('a-calendar', require('./components/ArticleCalendar.vue').default);
const app = new Vue({
el: '#app'
});
<script src=" {{ mix('js/app.js') }}"></script>
<div id="app">
<a-calendar url="{{ url }}"></a-calendar>
</div>
ACalendar.vue
<template>
<div>
<v-calendar v-on:dayclick="dayclick"></v-calendar>
</div>
</template>
export default {
data(){
return {
items:[
],
isLoaded : false,
isLoading : false,
isError : false,
}
},
props: {
url : String
},
}
</script>
const mix = require('laravel-mix');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.webpackConfig({
plugins: [
new VuetifyLoaderPlugin(),
],
});
mix.js('resources/js/app.js', 'public/js')
.js('resources/js/chat.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.version();
app.scss
// Fonts
#import url('https://fonts.googleapis.com/css?family=Nunito');
// Variables
#import 'variables';
// Bootstrap
#import '~bootstrap/scss/bootstrap';
When I removed mix.webpackConfig and VuetifyLoaderPlugin,The calendar component works well.
After recently applied vuetify inside laravel 7 means with vuejs, I wasn't able to configure the vuetify actual settings, but that's what I have done and it works normal now.
Also I want to mention that vuetify has almost everything like calendars, tables buttons, forms etc...
resources/sass/app.scss
// Fonts
#import url('https://fonts.googleapis.com/css?family=Nunito');
// Variables
#import 'variables';
// Icons
#import '~#mdi/font/css/materialdesignicons.min.css';
#import '~material-design-icons-iconfont/dist/material-design-icons.css';
// Bootstrap
//#import '~bootstrap/scss/bootstrap';
// Vuetify
#import '~vuetify/dist/vuetify.min.css';
Note I have left the webpack.mix.js as it is
resources/js/app.js
require('./bootstrap');
window.Vue = require('vue');
import VueRouter from 'vue-router'
import Vuetify from 'vuetify';
Vue.use(VueRouter);
Vue.use(Vuetify);
import {routes} from './routes';
import App from './components/App.vue';
const app = new Vue({
el: '#app',
vuetify: new Vuetify(),
router: new VueRouter({mode: 'hash', routes}),
render: h => h(App)
});
View where components are rendering means where app id is located
//Inside head tag
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
//Inside body tag
<v-app id="app"></v-app>
<script src="{{ asset('js/app.js') }}"></script>
This way I have configured my newly vuejs project with vuetify inside laravel 7, everythings is working fine, I might have misconfigured something means there might be a good approach than mine. But for me it's working now.

Laravel Echo "Echo is not defined"

First of all thanks for reading. Let me explain the problem that I'm facing. So I installed Pusher and Laravel Echo successfully and tried to use it in my dash.blade.php, this is how I imported the app.js file: <script src="{{ asset('js/app')}}"></script>. After that I used this:
<script>
Echo.channel('channelDemoEvent')
.listen('eventTrigger', (e) => {
alert('Its working');
});
</script>
And when running it I get this error in chrome console: Uncaught ReferenceError: Echo is not defined
I searched on the internet for this error more than 2 hours now, and when I added window. before the Echo I got a different error, that error is this:
Uncaught TypeError: Cannot read property 'channel' of undefined
I have tried to comment these on the app.js because I read that that could make this error: Vue.component('example-component', require('./components/ExampleComponent.vue'));
window.Vue = require('vue');
const app = new Vue({
el: '#app',
});`
After commenting those I get the same error.
Thanks for reading & have a nice day.
Here are the steps
composer
Install pusher if you are using pusher
composer require pusher/pusher-php-server "~4.0"
NPM or Yarn
npm install --save laravel-echo pusher-js
If not using pusher then
npm install --save socket.io-client
Blade
Make sure that your template has csrf token like so
<meta name="csrf-token" content="{{ csrf_token() }}">
.env
In .env you should fill in your pusher information
PUSHER_APP_ID=yourpusherappid
PUSHER_APP_KEY=yourpusherappkey
PUSHER_APP_SECRET=yourpusherappsecret
PUSHER_APP_CLUSTER=yourpusherappcluster
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
webpack.mix.js
In webpack.mix.js
Make sure you have
const mix = require("laravel-mix");
require("dotenv").config();
bootstrap.js
In resources/js/bootstrap.js
Make sure you have uncommented
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
import Echo from "laravel-echo";
window.Pusher = require("pusher-js");
window.Echo = new Echo({
broadcaster: "pusher",
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true
});
Compile
Don't forget to recompile your js files
NPM run watch
NPM run dev
NPM run prod
Config Cache
Sometimes you may need to clear the cache so that changes take effect run the following command
php artisan config:clear
Thanks for upvote
For me the problem was in loading Echo Script before initialization,
So i had to make the listener start after the whole page is loaded
window.addEventListener('load', () =>{
Echo.join(`chat`)
.here((users) => {
console.log(users)
})
.joining((user) => {
console.log(user.name);
})
.leaving((user) => {
console.log(user.name);
})
.error((error) => {
console.error(error);
});
})
Here are some things you can check/do that might resolve your issue:
Make sure that you have uncommented these lines in bootstrap.js
bootstrap.js
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true
});
Did you run npm run dev, npm run prod or npm run watch after making your changes?
I am not confident with your js importation. asset('js/app') will return http://localhost/js/app. You probably have to add .js at the end to have everything imported properly.
Check that your js/app.js importation is positioned before your <script></script> tag.
I have used Laravel echo in pure JS and that happened because document wasn't loaded.
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
Echo.listen(...);
}
}
Please follow the below sequence of code
first set window variable
second config vue
window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'http://127.0.0.1:6001'
})
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
`

Laravel Mix (Vue + Stylus). Blank page on npm run watch

I start up a new Laravel + Vue + Stylus project, and i can't normally work because i always got blank page when adding/editing some styles on .styl files. And when i edit my .vue templates it come back to normal state.
My main.js file:
import Vue from 'vue';
import VueRouter from 'vue-router';
import { routes } from './routes/index';
import App from './App.vue';
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes
});
new Vue({
el: '#app',
router,
render: h => h(App)
});
My webpack.mix.js file:
mix.js('resources/assets/js/main.js', 'public/js')
.stylus('resources/assets/stylus/app.styl', 'public/css')
.browserSync('localhost:8000');
Some strange thing that i noticed is that when i save my .styl file i got main.js like prod version(not compiled) and in console has an error:
Uncaught SyntaxError: Unexpected token import
If i save this file again i got normal compiled main.js file, but it doesn't render my App
And finally when i edit .vue templates all works perfect.

Unknown custom element Vue - Laravel

Not sure what happened but this stop working today in my laravel project:
App.js
import { SweetModal, SweetModalTab } from 'sweet-modal-vue'
Vue.component('SweetModal', SweetModal);
in my php file:
<sweet-modal ref="challengeModal"></sweet-modal>
It was working until I had to re install all my node modules. I know the sweet-modal-vue module is in my node_modules.
I have also tried:
Vue.component('sweet-modal', SweetModal);
and:
const app = new Vue({
el: '#app',
components:{
SweetModal
}
});

Resources