在 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 协议》,转载必须注明作者和本文链接