在 laravel 中结合 vite 搭建 vue 应用 | laravel china 社区-大发黄金版app下载

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项目中安装的vue和vite插件。
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 vueh1>
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文件中引入:
<html lang="{{ str_replace('_', '-', app()->getlocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>laraveltitle>
        @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,可以看到页面效果了。
原文:
本作品采用《cc 协议》,转载必须注明作者和本文链接
