未捕获的ReferenceError:使用laravel-mix Webpack时未定义Vue

时间:2018-07-30 08:27:33

标签: laravel webpack vue.js laravel-mix

我正在将laravel-mix与webpack一起使用以包含Vue,但这总是会导致此错误:

  

未捕获的ReferenceError:未定义Vue

我使用以下命令来编译文件:

  

npm run dev

我从此文件编译Vue: webpack.mix.js

let mix = require('laravel-mix');

mix.webpackConfig({
    externals: {
        'vue':'Vue',
        'vuejs-dialog': 'VuejsDialog'
    }
});

mix.js('resources/assets/js/app.js', 'public/js')
    .sass('resources/assets/sass/app.scss', 'public/css');

我使用它来将其包含在我的html文件中:

<script src="{{ URL::asset('js/app.js') }}"></script>

package.json

{
"private": true,
"scripts": {
  "dev": "npm run development",
  "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
  "watch": "npm run development -- --watch",
  "watch-poll": "npm run watch -- --watch-poll",
  "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
  "prod": "npm run production",
  "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"devDependencies": {
  "axios": "^0.18",
  "bootstrap": "^4.0.0",
  "popper.js": "^1.12",
  "cross-env": "^5.1",
  "jquery": "^3.2",
  "laravel-mix": "^2.0",
  "lodash": "^4.17.4",
  "vue": "^2.5.7"
},
"dependencies": {
  "axios": "^0.18.0",
  "vuedialog": "^1.0.0"
}

}

资源/资产/js/app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
    el: '#app'
});

我已经尝试过这种方法,但是仍然给我未定义的错误: https://laravel.com/docs/5.6/mix#working-with-scripts

该如何解决? 希望可以有人帮帮我。谢谢。

2 个答案:

答案 0 :(得分:1)

在实际的应用程序脚本中需要Vue。当前导入Vue的位置在mix config文件中,该文件用于生成构建文件。

在此处的Laravel存储库中查看app.js

https://github.com/laravel/laravel/blob/master/resources/assets/js/app.js

'resources/assets/js/app.js'需要:

window.Vue = require('vue');
const app = new Vue({
    el: '#app'
});

由于您使用的是Laravel Mix,因此应使用mix函数包含捆绑的资产:

<script src="{{ mix('/js/app.js') }}"></script>

答案 1 :(得分:0)

只需从定义defer的{​​{1}}标签中删除script属性即可解决此错误。