PHP+Vue本地运行报错:Uncaught SyntaxError: Unexpected token '<'
问题描述
接手一个PHP+Vue项目,线上服务器可正常运行。将文件下载到本地后,使用Wampserver启动时,访问网站出现错误:Uncaught SyntaxError: Unexpected token '<' (at app.js:1:1)。排查发现:在开发者工具中查看app.js和app.css,返回的是base.blade.php的HTML内容而非对应代码,但本地项目文件夹中的app.js确实存在正常代码,疑似服务端返回了错误文件。本人无PHP开发经验,寻求解决方法。
相关代码
app.js
require('./bootstrap'); window.Vue = require('vue'); const files = require.context('./components', true, /\.vue$/i) files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default)) const app = new Vue({ el: '#app', }); $(function () { $('[data-toggle="tooltip"]').tooltip() })
bootstrap.js
window._ = require('lodash'); try { window.Popper = require('popper.js').default; window.$ = window.jQuery = require('jquery'); require('bootstrap'); } catch (e) {} window.axios = require('axios'); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
base.blade.php
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@yield('title')</title> <link href="{{ env('APP_ENV') == 'development' ? mix('css/app.css') : asset('css/app.css') }}" rel="stylesheet" defer> <script src="{{ env('APP_ENV') == 'development' ? mix('js/app.js') : asset('js/app.js') }}" defer></script> {{-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> --}} <link href="https://fonts.googleapis.com/css?family=Roboto:200,300,400,500,600,700,800,900" rel="stylesheet"> @stack('head') @stack('style') </head> <body> <div id="app"> @yield('main') </div> </body> @stack('script') </html>
解决步骤
检查.env文件的环境配置
找到项目根目录的.env文件(没有的话复制.env.example并重命名为.env),确保APP_ENV=development。因为模板里开发环境用mix()方法加载资源,生产环境用asset(),环境配置错误会导致资源路径解析失败。安装前端依赖并编译资源
项目使用了Laravel Mix(从mix()方法判断),需先安装Node.js,然后在项目根目录打开命令行执行:npm install npm run dev执行后会生成
public/mix-manifest.json,mix()方法依赖这个文件定位资源。如果缺少该文件,请求会返回404,服务器可能将404请求重定向到首页,导致资源加载到HTML内容。配置Wampserver虚拟主机
确保虚拟主机指向项目的public目录(Laravel项目的入口是public/index.php),避免路径错误。- 打开Wampserver的
httpd-vhosts.conf,添加配置:<VirtualHost *:80> ServerName local-project.test DocumentRoot "C:/wamp64/www/your-project/public" <Directory "C:/wamp64/www/your-project/public"> AllowOverride All Require local </Directory> </VirtualHost> - 在本地
hosts文件(路径:C:\Windows\System32\drivers\etc\hosts)添加:127.0.0.1 local-project.test - 重启Wampserver,用
local-project.test访问项目,而非localhost/your-project。
- 打开Wampserver的
验证public目录资源
如果使用生产环境模式(APP_ENV=production),需确认public/css/app.css和public/js/app.js存在且路径正确,检查文件权限是否正常。
内容的提问来源于stack exchange,提问作者CNacho

