让vue文件直接在浏览器中运行

让 Vue 原生支持在浏览器中直接运行 .vue 文件,这才符合“渐进式框架”的定位!webpack 学不好或者不想学或者嫌麻烦,就可以使用插件在浏览器中直接编译运行 .vue 文件!
这样项目开发起来就不用去配置繁琐的 Webpack,不用等待 Webpack 的编译过程。
在 Vue2 时代,为了能够快速开发,可以使用 FranckFreiburger 开发的 http-vue-loader 插件,它可以使浏览器直接运行 .vue 文件,方便完善代码,实现快速开发;
https://github.com/FranckFreiburger/http-vue-loader
在 Vue3 时代,FranckFreiburger 又开发了 vue3-sfc-loader 插件,可以使浏览器直接运行 Vue3 的 .vue 文件。
https://github.com/FranckFreiburger/vue3-sfc-loader
我非常喜欢 FranckFreiburger 的这两个项目,而且已经在实际项目中使用了,特别好用!唯一一点是不太方便调试。
快速开始
官方示例如下,你需要创建 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>
然后你需要创建 myComponent.vue 文件,文件内容如下:
<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>
最后启动项目:
npm install expressnode -e "require('express')().use(require('express').static(__dirname, {index:'index.html'})).listen(8181)"
访问地址:http://127.0.0.1:8181
评论
