讓vue文件直接在瀏覽器中運(yùn)行

讓 Vue 原生支持在瀏覽器中直接運(yùn)行 .vue 文件,這才符合“漸進(jìn)式框架”的定位!webpack 學(xué)不好或者不想學(xué)或者嫌麻煩,就可以使用插件在瀏覽器中直接編譯運(yùn)行 .vue 文件!
這樣項(xiàng)目開發(fā)起來就不用去配置繁瑣的 Webpack,不用等待 Webpack 的編譯過程。
在 Vue2 時(shí)代,為了能夠快速開發(fā),可以使用 FranckFreiburger 開發(fā)的 http-vue-loader 插件,它可以使瀏覽器直接運(yùn)行 .vue 文件,方便完善代碼,實(shí)現(xiàn)快速開發(fā);
https://github.com/FranckFreiburger/http-vue-loader
在 Vue3 時(shí)代,F(xiàn)ranckFreiburger 又開發(fā)了 vue3-sfc-loader 插件,可以使瀏覽器直接運(yùn)行 Vue3 的 .vue 文件。
https://github.com/FranckFreiburger/vue3-sfc-loader
我非常喜歡 FranckFreiburger 的這兩個(gè)項(xiàng)目,而且已經(jīng)在實(shí)際項(xiàng)目中使用了,特別好用!唯一一點(diǎn)是不太方便調(diào)試。
快速開始
官方示例如下,你需要?jiǎng)?chuàng)建 index.html 文件:
<html><body><div id="app">div><script src="https://unpkg.com/vue@next">script><script src="https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js">script><script>const options = {moduleCache: {vue: Vue},async getFile(url) {const res = await fetch(url);if ( !res.ok )throw Object.assign(new Error(url+' '+res.statusText), { res });return await res.text();},addStyle(textContent) {const style = Object.assign(document.createElement('style'), { textContent });const ref = document.head.getElementsByTagName('style')[0] || null;document.head.insertBefore(style, ref);},}const { loadModule } = window['vue3-sfc-loader'];const app = Vue.createApp({components: {'my-component': Vue.defineAsyncComponent( () => loadModule('./myComponent.vue', options) )},template: '' });app.mount('#app');script>body>html>
然后你需要?jiǎng)?chuàng)建 myComponent.vue 文件,文件內(nèi)容如下:
<template><div class="title">hello worlddiv>template><script>export default {setup () {console.log('hello world')}}script><style scoped>.title {font-size: 40px;color: red;}style>
最后啟動(dòng)項(xiàng)目:
npm install expressnode -e "require('express')().use(require('express').static(__dirname, {index:'index.html'})).listen(8181)"
訪問地址:http://127.0.0.1:8181
評(píng)論
圖片
表情
