Git Product home page Git Product logo

vue3-sfc-loader's People

Contributors

dependabot[bot] avatar franckfreiburger avatar toilal avatar volkipp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue3-sfc-loader's Issues

vue file use import js file

vue file content:

<template>
  <div>
    hello user detail
  </div>
</template>

<script type="module">
import {user} from "./test.js"

export default {
  name: "userDetail",
  data() {
    return {}
  },
  created() {
    console.log(user)
  },
  methods: {}
}
</script>

test.js file content

export const user = {
    userName: "root",
    password: "zfs1111"
}

error message

SyntaxError: 'import' and 'export' may appear only with 'sourceType: "module"' (1:0)
    at De._raise (vue3-sfc-loader.js:19)
    at De.raiseWithData (vue3-sfc-loader.js:19)
    at De.assertModuleNodeAllowed (vue3-sfc-loader.js:19)
    at De.parseStatementContent (vue3-sfc-loader.js:19)
    at De.parseStatement (vue3-sfc-loader.js:19)
    at De.parseBlockOrModuleBlockBody (vue3-sfc-loader.js:19)
    at De.parseBlockBody (vue3-sfc-loader.js:19)
    at De.parseProgram (vue3-sfc-loader.js:19)
    at De.parseTopLevel (vue3-sfc-loader.js:19)
    at De.parse (vue3-sfc-loader.js:19)
Promise.catch (async)
extractComponentsGuards @ vue-router.js:1991
(anonymous) @ vue-router.js:3070
Promise.then (async)
navigate @ vue-router.js:3065
pushWithRedirect @ vue-router.js:2961
push @ vue-router.js:2901
loadMenuRouter @ VM1757:103
eval @ VM1757:57
Promise.then (async)
nextTick @ vue.global.js:1457
created @ VM1757:55
callWithErrorHandling @ vue.global.js:1370
callWithAsyncErrorHandling @ vue.global.js:1379
callSyncHook @ vue.global.js:7107
applyOptions @ vue.global.js:7038
finishComponentSetup @ vue.global.js:7718
setupStatefulComponent @ vue.global.js:7649
setupComponent @ vue.global.js:7589
mountComponent @ vue.global.js:5311
processComponent @ vue.global.js:5287
patch @ vue.global.js:4915
componentEffect @ vue.global.js:5403
reactiveEffect @ vue.global.js:410
effect @ vue.global.js:385
setupRenderEffect @ vue.global.js:5368
mountComponent @ vue.global.js:5327
processComponent @ vue.global.js:5287
patch @ vue.global.js:4915
render @ vue.global.js:5988
mount @ vue.global.js:4253
app.mount @ vue.global.js:9375
(anonymous) @ global.config.js:339
mount @ global.config.js:338
(anonymous) @ index.js:14
Promise.then (async)
(anonymous) @ index.js:14
Promise.then (async)
(anonymous) @ index.js:13
Promise.then (async)
(anonymous) @ index.js:13
Promise.then (async)
(anonymous) @ index.js:13
Promise.then (async)
(anonymous) @ index.js:12
Promise.then (async)
(anonymous) @ index.js:12
async function (async)
(anonymous) @ index.js:10
(anonymous) @ index.js:15
vue-router.js:1995 Uncaught (in promise) Error: Couldn't resolve component "default" at "/userDetail"
    at vue-router.js:1995

Breakpoints

Is it, currently, possible to add breakpoints in Dev Tools - like pure HTML/JS? If not, is it possible to add them in code?

Finally, if neither are possible, will this be a feature in the future?

Unable to use with Vuetify

Describe the bug

Hello, I currently have a Vuetify app that I wish to use with the vue-sf3-loader. However, I can't seem to figure out how to make it work with Vuetify. Specifically, if the content retrieved by loadModule contains any Vuetify elements (e.g. v-btn, v-card, etc.) I get the following error:

Unknown custom element: <v-text-field> - did you register the component correctly? For recursive components, make sure to provide the "name" option

This is a basic snippet of what is happening (see here for the exact code):

<template>
  <v-app>
    <v-app-bar
      app
      color="primary"
      dark
    >
      <div class="d-flex align-center">
        <v-img
          alt="Vuetify Logo"
          class="shrink mr-2"
          contain
          src="https://cdn.vuetifyjs.com/images/logos/vuetify-logo-dark.png"
          transition="scale-transition"
          width="40"
        />

        <v-img
          alt="Vuetify Name"
          class="shrink mt-1 hidden-sm-and-down"
          contain
          min-width="100"
          src="https://cdn.vuetifyjs.com/images/logos/vuetify-name-dark.png"
          width="100"
        />
      </div>

      <v-spacer></v-spacer>

      <v-btn
        href="https://github.com/vuetifyjs/vuetify/releases/latest"
        target="_blank"
        text
      >
        <span class="mr-2">Latest Release</span>
        <v-icon>mdi-open-in-new</v-icon>
      </v-btn>
    </v-app-bar>

    <v-main>
      <HelloWorld/>
      <MyComponent/>
    </v-main>
  </v-app>
</template>

<script>
import HelloWorld from './components/HelloWorld';
import Vue from 'vue';
import { loadModule } from 'vue3-sfc-loader/dist/vue2-sfc-loader';

const sfcContent = '<template><v-text-field></v-text-field></template>';

const options = {
  moduleCache: {
    vue: Vue
  },
  getFile: async (url) => {
    if ( url === '/myComponent.vue' )
      return Promise.resolve(sfcContent);
  },
  addStyle: () => {},
}

export default {
  name: 'App',

  components: {
    HelloWorld,
    MyComponent: () => loadModule('/myComponent.vue', options)
  },

  data: () => ({
    //
  }),
};
</script>

I was hoping someone could help me figure out how to make it so that Vuetify elements are recognized by loadModule.

To Reproduce

  1. git clone [email protected]:dbellinghoven/referral.git
  2. cd referral/ui
  3. yarn serve
  4. Go to localhost:8080 in your browser
  5. Open up the console
  6. The aforementioned error should appear

Expected behavior

Versions

  • Browser (name & version): Google Chrome Version 91.0.4472.106 (Official Build) (x86_64)
  • vue3-sfc-loader: 0.7.3
  • Vue 2: 2.6.11
  • Vuetify: 2.4.0

Additional context

i use vue2-sfc-loader ,vsersion 0.8.3 ,hava one erro

vue version : v2.6.14
vue2-sfc-loader version : 0.8.3
error:

Uncaught (in promise) TypeError: t is not a function
    at vue2-sfc-loader.js:65
    at vue2-sfc-loader.js:65
    at async P (vue2-sfc-loader.js:65)
    at async Module.N (vue2-sfc-loader.js:65)

SharedArrayBuffer will require cross-origin isolation as of M91

Describe the bug
I am using vue2-sfc-loader but I got this warning on chrome console.

vue2-sfc-loader.js:59 [Deprecation] SharedArrayBuffer will require cross-origin isolation as of M91, around May 2021. See https://developer.chrome.com/blog/enabling-shared-array-buffer/ for more details.

To Reproduce
Reference vue2-sfc-loader

Expected behavior

No warning should be displayed.

Versions

  • Microsoft Edge: Version 89.0.774.75 (Official build) (64-bit)
  • vue2-sfc-loader:

Additional context
image

use babel source instead of babel packages (@babel/*)

I would like to embed babel using source version (github.com/babel) instead of packaged version (npm @babel/*) in order to benefits of a better (webpack) tree-shaking (@babel/* is cjs whereas github.com/babel is mjs/ts) and to reduce final bundle size.

I need to make TypeScript to resolve any node_modules/@babel/* to node_modules/babel/packages/babel-*/src

I tried with compilerOptions.paths with no success :

	paths: {
		'@babel/code-frame': ['babel/packages/babel-code-frame/src'],
	}

Is there a trick to make any require to @babel/* to point to babel/packages/babel-*/src ?

BTW, In the webpack configuration file, I use:

resolve: {
	alias: {
		'@babel/code-frame': 'babel/backages/babel-code-frame/src',

and I'm looking for the equivalent for typescript.

Any examples for vue2-sfc-loader?

I can't seem to figure out how to use the vue2-sfc-loader. If I simply include https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue2-sfc-loader.js, nothing seems to get added to the window object, so code like

const { loadModule } = window['vue3-sfc-loader'];

or

const { loadModule } = window['vue2-sfc-loader'];

just fails. Does the Vue 2 version work different from the Vue 3 version somehow? Unfortunately there are no example for the Vue 2 version, and I really don't want to dig through the minified source to try and find out how this is supposed to work, so it would be good if you could provide an example of how the Vue 2 version is supposed to be used.

Disabled vue3-sfc-loader cache

Hi,
is it possible to disable the cache of vue3-sfc-loader? I need it because every time I change vue components the only way I have to see the changes is to clear the cache. When I was using httpvueloader I had solved it by adding a timestamp as a query string when importing a component, is it possible to do that again?

error on importing a redirected file

Describe the bug

I am importing a unpkg.com file, wich gets redirected to the reqal file. Fetch gets it, as in the examples, but die module ... shows an error:

To Reproduce
in a the first .vue component, app.vue showing a hello world, and having:

import { hexToRgba } from "//unpkg.com/hex-and-rgba";

results in https://unpkg.com/[email protected]/index.js -- the Chrome Network tab shows the redirected request, dumping right in the getFiles() function shows the content.

and the error:

Uncaught (in promise) ReferenceError: hexToRgba is not defined
    at Object.eval (eval at A (vue3-sfc-loader:75),
    at A (vue3-sfc-loader:75)
    at vue3-sfc-loader:75
    at async vue3-sfc-loader:75
    at async w (vue3-sfc-loader:75)
    at async j (vue3-sfc-loader:75)

Expected behavior
I believe, any redirect should work.

Versions

  • Browser (name & version): Chrome latest
  • vue3-sfc-loader: 0.8.0

Broken behaviour in Chrome 75

When using sfc-loader 0.8.0 and onwards, Chrome 75 fails with the following error:
Uncaught SyntaxError: Unexpected token ? on line 82 in vue3-sfc-loader.js (minified).

The line is: https://github.com/FranckFreiburger/vue3-sfc-loader/blob/v0.8.4/src/index.ts#L103
Simply swapping the operator from ?? to || makes it work again.

To Reproduce

  1. Run the minimal reproduction below on Chrome 75 (or any other browser without support for the nullish coalescing operator)
  2. Observe the execution stopping when it encounters ?? in line 82 from the minified script.

Expected behavior
No nullish coalescing operators would be in the minified script, thus making browsers load it with no problem.

Versions

  • Browser (name & version): Chrome 75
  • vue3-sfc-loader: 0.8.4

Additional context

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue3 SFC Loader Chrome 75 Breakage Repro</title>
  </head>

  <body>
    <div id="app"></div>

    <script src="https://unpkg.com/[email protected]"></script>
    <script src="https://unpkg.com/[email protected]/dist/vue3-sfc-loader.js"></script>
    <script>
      const options = {
        moduleCache: {
          vue: window["Vue"],
        },
      };

      const app = Vue.createApp({
        components: {
          hello: {
            template: "Hello world",
          },
        },

        template: `<hello></hello>`,
      });

      app.mount("#app");
    </script>
  </body>
</html>

http-vue-loader migration guide

I just updated a repo from http-vue-loader to vue3-sfc-loader. Here are my notes which could be used as part of a migration guide.

Notes:

  1. Convert from Vue 2 to Vue 3:
    • Change const app = new Vue({ el: '#app' });
    • To const app = Vue.createApp({}); app.mount('#app');
  2. Convert components from module.exports = {}; to export default {};
  3. Convert data: {} to data: function () { return {}; }
    • Otherwise you get Uncaught TypeError: dataFn.call is not a function error

I created this function which meant I didn't need to change the components section at all, keeping it much cleaner:

function httpVueLoader (componentPath) {
  const sfcLoaderOptions = {
    moduleCache: {
      vue: Vue
    },
    getFile: async function (url) {
      const response = await fetch(url);
      if (!response.ok) {
        throw Object.assign(new Error(response.statusText + ' ' + url), { response });
      }
      return await response.text();
    },
    addStyle: function (textContent) {
      const style = Object.assign(document.createElement('style'), { textContent });
      const reference = document.head.getElementsByTagName('style')[0] || null;
      document.head.insertBefore(style, reference);
    }
  };
  return Vue.defineAsyncComponent(function () {
    return window['vue3-sfc-loader'].loadModule(componentPath, sfcLoaderOptions);
  });
}

so my components still look like this, and it works:

  components: {
    'github-corner': httpVueLoader('/_components/github-corner.vue'),
    'site-logo': httpVueLoader('/_components/site-logo.vue'),
    'news-alerts': httpVueLoader('/_components/news-alerts.vue'),
    'base-card': httpVueLoader('/_components/base-card.vue'),
    'unreviewed-card': httpVueLoader('/_components/unreviewed-card.vue')
  },

Slow parsing?

First of all, great work!

But I tested the load-from-string example and the timing is just bad for production. It takes ~70ms to create the component from a simple string. I don't assume the problem is the content, since there is nothing great to parse.

So is it the invocation of the parser itself? Doing unnecessary steps or are the functions so big it takes so much time to load it? Can this be optimized?

const options = {
    moduleCache: {
        vue: Vue,
    },
    getFile() {
        return `<template>nothing</template>`
    },
    addStyle() { }
}

let begin = (new Date).getTime()
loadModule("foo.vue", options).then(() => {
    const elapsed = (new Date).getTime() - begin
    console.log("component created after " + elapsed + " ms")
})

Script

Hi,

I think there is a bug in v0.4.2
image

image

Perhaps, it's because I use:
<script setup lang='ts'>

It's ok if I use v0.4.1.

how to debug?

hi,
is there a way to generate or link the script that which was complied to a sourceMap file ? because it is impossible to debug from what i see.

Typescript support and examples

Describe the bug

Problems while creating the Options field for loadModule

To Reproduce

<template>
  <component :is="computedComponent" />
</template>

<script lang="ts">
import { loadModule } from "vue3-sfc-loader/src/index"
import { defineComponent, defineAsyncComponent } from "vue"

const options = {
    async getFile(url: string) {
        const res = await fetch(url)
        if ( !res.ok )
            throw Object.assign(new Error(`${res.statusText} ${url}`), { res })
        return await res.text()
    },
    addStyle(textContent: any) {

        const style = Object.assign(document.createElement("style"), { textContent })
        const ref = document.head.getElementsByTagName("style")[0] || null
        document.head.insertBefore(style, ref)
    },
}

export default defineComponent({
    data() {
        return {
            currentComponent: "./DashBoard.vue",
        }
    },
    props: {
        url: {
            type: String,
            required: true
        },
    },
    computed: {
        computedComponent() {
            const currentComponent: String = this.url // the trick is here
            return defineAsyncComponent( () => loadModule(currentComponent, options) )
        }
    },
})
</script>

Expected behavior
It should works but it gets:

ERROR in src/components/Page.vue:41:77
TS2345: Argument of type '{ getFile(url: string): Promise<string>; addStyle(textContent: any): void; }' is not assignable to parameter of type 'Options'.
  Type '{ getFile(url: string): Promise<string>; addStyle(textContent: any): void; }' is missing the following properties from type 'Options': pathResolve, getResource
    39 |         computedComponent() {
    40 |             const currentComponent: String = this.url // the trick is here
  > 41 |             return defineAsyncComponent( () => loadModule(currentComponent, options) )
       |                                                                             ^^^^^^^
    42 |         }
    43 |     },
    44 | })


Versions

  • Compiling via typescript:
  • vue3-sfc-loader: latest

Vue 3.2 support

Vue 3.2 looks really interesting, particularly the new syntax sugar.

Do you know if it's safe to upgrade it to if we're using your library to load vue files?

Thanks for the great work.

H.

Php file in place of Vue file

Hello,

First thanks for this great tool.

My problem. I just want to use a .php file in place of a .vue file into the loadModule function but it's not working.
it told me : "TypeError: Unable to handle .php files (js/vue/components/hello_world/test.php), see additionalModuleHandlers"

i'v try to add in config:

additionalModuleHandlers:
{
'.php': function(source, path, options)
{
return source;
}
}

But it's not working at all. May be i'm doing some wrong ?

Thanks

Example with imported JSON

Is your feature request related to a problem? Please describe.

i have looked through the examples and can't see the necessary options{} magic to allow import data from '/path/to/some.json'; to work.

Describe the solution you'd like

Automatic handling of JSON in a vue SFC. If not automatic, then the functions to add to options{}

Describe alternatives you've considered

Additional context

Add binary data support

Is your feature request related to a problem? Please describe.
At the moment it is not possible to require binary data (eg. import logo from "../images/logo.png";)

Describe the solution you'd like
The solution is to mimic how fetch() handle this :

  1. fetch the resource
  2. use the right API to get the data as text or as binary (see https://developer.mozilla.org/en-US/docs/Web/API/Body)

Additional context
see discussion #60

** Note **
This implies a breaking changes for the API options.getFile() and type File

getFile() will continue to support a simple string as return value but the object form will be :
{ type, getContentData } instead of { type, content }

Q: how to import component dynamicly

Hello,

frist thanks foryour great work!!

i'm currently rewriting some code and i have a popup-component that will get a component-name and props
but mostly the components are not loaded, so i thought i could just load them if missing

i can check if the component is aviable, i can fetch the component, but how can i "add" the loaded component to the current instance?
(i know that this may be behind he scope of your project, but maybe you know?)

how to use <style lang='scss'> in vue sfc?

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Can't build using vue2-sfc-loader ESM with rollup/vite

Describe the bug

I try to build an app using vue2-sfc-loader (esm) and vite.

It works properly in dev mode, but when building the app, it fails. Vite is building with rollup under the hood, so it may likely be a configuration issue, but I can't understand the following error.

[commonjs] Unexpected token (15:124277) in /home/toilal/projects/OFB-ESTAMP/frontend-vite/node_modules/vue3-sfc-loader/dist/vue2-sfc-loader.esm.js

To Reproduce

Expected behavior

Versions

  • Browser (name & version):
  • vue2-sfc-loader: v0.7.3

Additional context

How to use plugins?

Thanks for this great library, looks promising for a small project I'd like to get off the ground.

I'm just a bit unsure as to how plugins should be used when creating the Vue app instance.
The examples from the Vue documentation show:

import i18nPlugin from './plugins/i18n'

But how should I use this without webpack?

less.render not support syncImport:true rendering @import

Describe the bug

less.render() does not support synchronous rendering @import.
The syncImport attribute is invalid. If there is an @import string and syncImport: true, the callback function will never be called

The code from @vue/compiler-sfc/dist/compiler-sfc.cjs.js

nodeLess.render(getSource(source, options.filename, options.additionalData), Object.assign(Object.assign({}, options), { syncImport: true }), (err, output) => {
        error = err;
        result = output;
    });

To Reproduce

Expected behavior

Versions

Additional context

Poor compatibility of v0.8.0 version

Poor compatibility of v0.8.0 version


v0.7.3

Chromium :69.0.3497.81 compatible
Firefox : 59.0.1 compatible


v0.8.0

Chromium :69.0.3497.81 Not compatible
Firefox : 59.0.1 Not compatible

error
Uncaught SyntaxError: Unexpected token
Uncaught TypeError: Cannot destructure property loadModule of 'undefined' or 'null'.

Roadmap

  • core

    • add binary support in order to support image resources (eg. import logo from "../images/logo.png";)
    • make babel transpilation optional for non-.vue modules
  • translate to TypeScript

    • in progress
    • done
  • replace npm with yarn

    • in progress
    • done
  • replace @babel/preset-env with babel-polyfills

    • in progress
    • done
  • leave Major version zero

    • stable public API
    • get enough feedback
    • ready for 1.0.0

background tasks

  • reduce dist/ size
  • enhance the doc
  • add unit tests
  • add more examples

import '***.css'

  • file:test.vue
<template>test</template>
<script>
import test from '../test.js' 
import '../test.css' // When I use it like this, the console gives an error
...
...
</script>

image

Uncaught TypeError: Cannot destructure property `loadModule` of 'undefined' or 'null'.

Android 11
Edge 45.09.4.5079

When I use the edge browser of the android phone, I get the following error

Uncaught TypeError: Cannot destructure property loadModule of 'undefined' or 'null'.

const options = {
    moduleCache: {
        vue: Vue
    },
    async getFile(url) {
        const res = await fetch(url)
        if (!res.ok)
            throw Object.assign(new Error(res.statusText + " " + url), { res })
        return {
            getContentData: (asBinary) =>
                asBinary ? res.arrayBuffer() : 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']

Describe the bug

To Reproduce

Expected behavior

Versions

  • Browser (name & version):
  • vue3-sfc-loader:

Additional context

Create modules from strings

Describe the bug
The examples show that we can use createSFCModule, however I'm only able to use loadModule.

To Reproduce
Steps to reproduce the behavior:

  1. Add the latest vue3-sfc-loader to the <head>.
  2. Add a script tag with const { createSFCModule } = window["vue3-sfc-loader"];
  3. Try to use the function.
  4. See the error (createSFCModule is undefined):
    Uncaught TypeError: createSFCModule is not a function

Expected behavior
createSFCModule should create a new component from a single file component source string.

Desktop (please complete the following information):

  • OS: Manjaro Linux
  • Browser: Firefox
  • Version: 83

vue3-sfc-loader don't support <template #title>,but vue2-sfc-loader is ok.

Describe the bug
I use vue3-sfc-loader and ElementPlus framework,use

<el-submenu index="2">
  <template #title>我的工作台</template>
  <el-menu-item index="2-1">选项1</el-menu-item>
</el-submenu>

,report warn, but i try vue2-sfc-loader and ElementUI ,it's ok.

Versions

  • Browser (name & version):chrome 90
  • vue3-sfc-loader: 0.8
  • vue2-sfc-loader:0.8

support scss file and <style lang="scss" scoped>

the package vue-compile-sfc does not support async function, in brower sass.js doesnt support sync, the fix demo is in my fork branch(https://github.com/jeryqwq/vue3-sfc-loader/blob/main/test/demo.html), or wait for vue3 update(vuejs/core#5231)

 sass: { async  render(args){
        const { data, file, filename, outFile, sourceMap } = args
          return new Promise((reslove, reject) => {
            sass.compile(data, function(result) {
              reslove({
                css: result.text,
                stats: {}
              })
            });
          })
        } }

Importing as ES Module

Is your feature request related to a problem? Please describe.
Currently to use vue3-sfc-loader it must be injected in the global namespace and is not possible to load it is as an es module.

Describe the solution you'd like
I'd like to be able to import as an es module with loadModule being the default export (perhaps have version as a named export only), Vue 3 itself already supports being loaded as an es module, and perhaps include a default options so it becomes optional.
Describe alternatives you've considered

Additional context
I believe that an issue that may come up to support this (I am still new to Vue 3 , so take with a grain of salt), Vue 3 doesn't export a default "Vue"component like previous 2.x esm versions it only has named exports, this could affect

 moduleCache: {
        vue: Vue,
    }

If I have misunderstood anything please let me know, thanks again!

Adding SFC minifcation/obfuscation

Hey Franck

Great library. I've been using it for a while. I like not having a compilation step / webpack.

I was wondering if you've tried adding minification/obfuscation of the SFC files somehow. I know that's not within the scope of what your library should do, but curious if you've come across a tool that can fit in to the picture.

Thanks and keep up the great work.

IE11 error "SCRIPT5017" when load vue2-sfc-loader.js

Hi Franck,

I build my own version(to support IE11) use the {"browserslist": "> 1%, last 2 versions, not ie <= 10"} and {"browserslist": "defaults"}, but in IE11 always encounter js error SCRIPT5017 point to the line "vue2-sfc-loader.js (9,360569)"
this error point to the vue2-sfc-loader.js.map:
parse() {
this.enterInitialScopes();

  • const file = this.startNode();

    const program = this.startNode();
    this.nextToken();
    file.errors = null;
    this.parseTopLevel(file, program);
    file.errors = this.state.errors;
    return file;
    }

what can I do to fix this issue?

Thanks,
Wallace

how to load js chunk file and css chunk file that build from a vue component use vue-cli

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

How to use in Vue3 project?

Hi, I create a vue3 project with vite2, code like this:

<template>
    <component :is="remoteComp"></component>
</template>

<script>
    import { defineAsyncComponent, getCurrentInstance } from 'vue'
    import { loadModule } from 'vue3-sfc-loader'

    /* <!-- */
    let content = `
            <template>
                <div class="dtDiv">
                    Hello, 这个是动态页面噢
                </div>
            </template>
    `;
    /* --> */
    
    export default {
        computed: {
            remoteComp (){
                let app = getCurrentInstance()
                return defineAsyncComponent(()=>loadModule(`Dys.vue`, {
                    moduleCache:{
                        vue: app
                    },
                    getFile(url) {
                        return Promise.resolve(content)
                    },

                    addStyle() { /* unused here */ },
                }))
            }
        }
    }
</script>

But it does not work, got error:

Uncaught (in promise) TypeError: (0 , _vue.openBlock/createTextNode) is not a function

So how can I create component from String, Thanks much!

supports asynchronous style preprocessors

From a client-side point of view, most style pre-processors provide an asynchronous rendering API, while other pre-processors do not support a sync rendering API at all.

Then it could be useful to support async style rendering.

this.$refs.someUserDefinedRef.$el becomes null the second time it is used

Hi Franck,

I'm still enjoying your library !

I noticed that if I define a ref for a child component. For example:

<template>
  ...
  <hiddenFileInput
    ref="filesInput"
    @loadedFiles="storeAttachments"
  ></hiddenFileInput>
...
<template>

and use it in a method, for example:

<scripts>
  ...
  methods: {
    selectAttachments() {
      this.$refs.filesInput.$el.click();
    },
  },
  ...
</scripts>

Then the second time the method is called, I get this error:

Uncaught TypeError: this.$refs.filesInput is null
    selectAttachments https://cdn.jsdelivr.net/npm/[email protected]/dist/vue3-sfc-loader.js line 22 > Function:63
...

It seems like I lose the reference, although the child component still exists.
So I ended up storing the ref in a data on the first call like so:

<scripts>
  ...
  data() {
    return {
      refFileInput: null,
    };
  },
  ...
  methods: {
    selectAttachments() {
      if (!this.refFileInput) {
        this.refFileInput = this.$refs.filesInput.$el;
      }
      this.refFileInput.click();
    },
  },
  ...
</scripts>

But isn't it a bug ?
Or is there something I don't understand or do right ?
As a side note is using a ref the right way to reference a child component ?

Thank you for your help,

Merci

Raphaël

Is it possible to import from an ES6 module in a component (SFC) ?

Hi,
First I wan't to thank you for this librairy which is going to be very useful for me.
I can't manage to import from a module inside a script tag of a .vue file
For example :

<template>
  <div class="test">Test</div>
</template>

<script>
import { label } from "./../tools.js";
export default {
  name: "appWorld",
  computed: {
    ...Vuex.mapState(["count"]),
  },
  mounted() {
    console.log(`Component ${this.$options.name} mounted - ${label}`);
  },
};
</script>

<style scoped>
div.test {
  color: red;
}
</style>

The line
_import { label } from "./../tools.js";_

raises the following error.

_'import' and 'export' may appear only with 'sourceType: "module"' (2:0)_

I tried adding type="module" to the script tag but it didn't work either.

Is it possible to do that ? How ?
Thank you for your answer

Raphael

speeds up the loading of third-party libraries

Is your feature request related to a problem? Please describe.
Loading 3rd party libraries could be very long since vue3-sfc-loader is processing every dependencies through babel (for CJS transformation and dependencies static analysis).
For instance, babylon.max.js takes around 17s to load.

Describe the solution you'd like
The simplest solution is to give control to the caller about what to transpile and what to not transpile.
eg. do not transpile babylon

    const options = {
      ...
      async handleModule(type, getContentData, path, options) {

        if ( path.toString().endsWith('babylon.max.js') )
          return createCJSModule(type, await getContentData(false), options)

        return undefined;
      },
      ...

These libraries must be leaves of the whole dependency graph since no static analysis will be performed on them.
These libraries must already be CJS (or obviously UMD).

Additional context
see #50

Parent is mounted before child is mounted

Describe the bug

The "mounted"-hook of a parent is called before "mounted"-hook of child.

I have a Component "MyParent" and a Component "MyChild". There is literally nothing in it just in the "mounted-hook" a console.log("Parent is mounted") and console.log("Child is moutned").

The result is:
"Parent is mounted"
"Child is mounted"

but i would expect that the result is
"Child is mounted"
"Parent is mounted"

To Reproduce
Write the two SFCs. Maybe do something in the child that cost a bit time. Run a console.log() in both and check the order.

Expected behavior
I expect that the child is mounted before the parent is mounted. Here is what i expect: https://codesandbox.io/s/peaceful-benz-m0ljx?file=/src/App.vue:275-318

Versions

  • Browser Google Chrome :
  • vue3-sfc-loader

`n.helpers.keys is not a function or its return value is not iterable`

I had to switch from unpkg to jsdelivr a few seconds ago because the latter was failing for all my users. Have you recently pushed an update? if so jsdelivr might start failing soon as well if it's just on the old one. Please have a look into this! Will try to grab a copy of the current working one.

jsDelivr CDN: https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js
UNPKG CDN: https://unpkg.com/vue3-sfc-loader

Error: n.helpers.keys is not a function or its return value is not iterable

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.