在 Laravel 中结合 Vite 搭建 Vue 应用


Laravel 是一个优雅的 PHP WEB框架,在早期的版本中,一般是采用Mix搭配webpack来构建前端资源。
Vue 是一个渐进式 JavaScript 框架,Vite 是下一代前端开发和构建工具。那么这个组合起来,堪称绝美

下面是我所使用的版本:

  • PHP 8.2
  • Laravel 11.8.0
  • Node 20.13
  • Vite 5.0
  • Vue 3.4

安装 Laravel 和 Vue

这里直接使用composer创建Laravel项目。

composer create-project laravel/laravel example-app

接下来,在Laravel项目中安装的package.json的中的默认依赖。

npm install

然后,在Laravel项目中安装的VueVite插件。

npm install --save-dev vue@latest
npm install --save-dev @vitejs/plugin-vue

配置 Vite

Vite的配置文件是vite.config.js,修改内容如下:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel(['resources/css/app.css', 'resources/js/app.js']),
        vue({
            template: {
                transformAssetUrls: {
                    // The Vue plugin will re-write asset URLs, when referenced
                    // in Single File Components, to point to the Laravel web
                    // server. Setting this to `null` allows the Laravel plugin
                    // to instead re-write asset URLs to point to the Vite
                    // server instead.
                    base: null,

                    // The Vue plugin will parse absolute URLs and treat them
                    // as absolute paths to files on disk. Setting this to
                    // `false` will leave absolute URLs un-touched so they can
                    // reference assets in the public directory as expected.
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

创建Vue应用并挂载组件

创建组件resources/js/components/App.vue,内容如下:

<template>
  <h1>Hello Laravel and Vue</h1>
</template>

resources/js目录下的app.js文件,内容如下:

import './bootstrap';
import { createApp, ref } from 'vue'
import App from '../components/App.vue'

createApp(App).mount('#app')

引入 Laravel 入口

resources/views/welcome.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>Laravel</title>

        @vite('resources/css/app.css')
    </head>
    <body id="app">

    </body>
    @vite('resources/js/app.js')
</html>

启动 Laravel 和 Vite 服务

Laravel项目根目录下,启动Laravel服务:

php artisan serve

Laravel项目根目录下,启动Vue服务:

npm run dev

然后,打开浏览器访问http://127.0.0.1:8000,可以看到页面效果了。

原文: 在 Laravel 中结合 Vite 搭建 Vue 应用

本作品采用《CC 协议》,转载必须注明作者和本文链接
专注于分享 Go、Java、Python、PHP、Node.js 等全栈技术开发领域知识,欢迎关注我的 技术圈
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 1

那么这个部署怎么部署?vue使用npm run build,是不是自动就弄到laravel 项目的public文件夹里面去了?会不会跟原本laravel的路由冲突?

10个月前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
26
粉丝
9
喜欢
76
收藏
65
排名:363
访问:2.6 万
私信
所有博文
社区赞助商