Giter VIP home page Giter VIP logo

require-vuejs's Introduction

require-vuejs

RequireJS plugin to async and dynamic load and parse .vue single file components

Codacy Badge Build Status codecov Code Climate

NPM

This library has only 4Kb ( minified ).

What this library can do

  • Real time integration
  • Don't need build to use
  • Used as RequireJS plugin
  • You can use syntax detection from your IDE
  • Suport for single file component
  • Work with or without extension
  • Support .html and .vue files
  • CSS inside component file

What this library can't do

  • Parse Jade and other templates
  • Scoped css

CDN

Development ( last version )

https://raw.githack.com/edgardleal/require-vuejs/master/dist/require-vuejs.js

For production usage: ( Fast CDN, long age cache and minified )

https://raw.githack.com/edgardleal/require-vuejs/master/dist/require-vuejs.min.js

Installation from NPM repository

npm install require-vuejs

Usage

This example on Codepen

File structure

app.js
component.vue
index.html

Source code example

index.html

    <!DOCTYPE html>
    <html>
        <head>
        <meta charset="utf-8" />
            <title>Require Vue</title>
        </head>
        <body>
            <div id="app">
                <my-component></my-component>
        </div>
            <script data-main="app" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.3/require.min.js" ></script>
        </body>
    </html>

Create your component: ( component.vue )

    <template>
      <div>
          {{text}}
      </div>
    
    </template>
    
    <script>
      define(["Vue"], function(Vue) {
          Vue.component("my-component", {
              template: template, // the variable template will be injected 
              data: function() {
                  return {"text": "Ok"};
              }
          });
        });
    </script>

Create your app code: ( app.js )

    requirejs.config({
        paths: {
            "Vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min",
            "vue": "https://rawgit.com/edgardleal/require-vue/master/dist/require-vuejs"
        },
        shim: {
            "Vue": {"exports": "Vue"}
        }
    });
    
	// to use component in your code with RequireJS: 
	// put a reference to your component file with or without extencion after 'vue!' 
    require(["Vue", "vue!component"], function(Vue){
        var app = new Vue({
            el: "#app"
        });
    });

Optimize ( r.js )

Create a build file to r.js. In this example we are using a file named build.js:

    ({
        baseUrl: ".",
        paths: {
            "Vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue",
            "vue": "require-vuejs" // full path to require-vuejs library file 
        },
        name: "app",
        out: "main-built.js"
    })

After create the file build.js with your build configuration execute this command:

    r.js -o build.js

Contributing

CONTRIBUTING

License

MIT

Code of Conduct

https://js.foundation/conduct/

require-vuejs's People

Contributors

codacy-badger avatar dannyfeliz avatar edgardleal avatar freire71 avatar jmuletr avatar kaystrobach avatar razbakov avatar richienb avatar shiyl962 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

require-vuejs's Issues

Use local vue files

Is there a simple way to load local vue components instead of querying even a local server?

awesome for load agnostic html templates

(Not an issue)

You realized this library is awesome for load agnostic html templates, without needing of using Vue?
I haven't found any requirejs lib for html like this.

Maybe this could be a really agnostic html template loader, and simply add "instructions" for Vue implementation. (or make a common core repo?)

love your work!

VueJS Version

Hello,

Have you tried to use the latest version of Vue ?
All seem ok until the 2.3.4 version, It must be a problem with requirejs

When I use the latest version, here is the error

TypeError: t is undefined[En savoir plus] vue.min.js:6:7661
ct https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js:6:7661
lt/l< https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js:6:8122
C/< https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js:6:1978
newContext/context.execCb http://localhost:9999/Scripts/Audit/require.js:1696:24
newContext/Module.prototype.check http://localhost:9999/Scripts/Audit/require.js:883:43
newContext/Module.prototype.enable/</< http://localhost:9999/Scripts/Audit/require.js:1139:29
bind/< http://localhost:9999/Scripts/Audit/require.js:134:20
newContext/Module.prototype.emit/< http://localhost:9999/Scripts/Audit/require.js:1189:21
each http://localhost:9999/Scripts/Audit/require.js:59:31
newContext/Module.prototype.emit http://localhost:9999/Scripts/Audit/require.js:1188:17
newContext/Module.prototype.check http://localhost:9999/Scripts/Audit/require.js:938:25
newContext/Module.prototype.enable http://localhost:9999/Scripts/Audit/require.js:1176:17
newContext/Module.prototype.init http://localhost:9999/Scripts/Audit/require.js:788:21
newContext/Module.prototype.callPlugin/</< http://localhost:9999/Scripts/Audit/require.js:982:33
bind/< http://localhost:9999/Scripts/Audit/require.js:134:20
newContext/Module.prototype.emit/< http://localhost:9999/Scripts/Audit/require.js:1189:21
each http://localhost:9999/Scripts/Audit/require.js:59:31
newContext/Module.prototype.emit http://localhost:9999/Scripts/Audit/require.js:1188:17
newContext/Module.prototype.check http://localhost:9999/Scripts/Audit/require.js:938:25
newContext/Module.prototype.enable http://localhost:9999/Scripts/Audit/require.js:1176:17
newContext/Module.prototype.init http://localhost:9999/Scripts/Audit/require.js:788:21
newContext/Module.prototype.callPlugin/</load< http://localhost:9999/Scripts/Audit/require.js:1014:25
bind/< http://localhost:9999/Scripts/Audit/require.js:134:20
newContext/context.execCb http://localhost:9999/Scripts/Audit/require.js:1696:24
newContext/Module.prototype.check http://localhost:9999/Scripts/Audit/require.js:883:43
newContext/Module.prototype.enable http://localhost:9999/Scripts/Audit/require.js:1176:17
newContext/Module.prototype.init http://localhost:9999/Scripts/Audit/require.js:788:21
localRequire/<

Does not works using Firefox

Hi! Thx for awesome plugin! But..

But it not works using FireFox (default IE in win10 - also):

2018-09-07 15-47-16

61.0.1 (64-bit) Linux Mint

How can I fix this?

PRE tag in Template

Hy,

In "template "tags, the "pre" tag does not preserve lines feed.
All text is displayed in one line....
I would like to display highlighted code

Regards

"define" statement with no semi cause error

cause error :

<template><div></div></template>
<script>
define(['Vue'],function(Vue){})
</script>
<style></style>

no error:

<template><div></div></template>
<script>
define(['Vue'],function(Vue){});
</script>
<style></style>

because the error code text passed to onload.fromText is:

(function (template) {
  define(['Vue'], function (Vue) {

  })  // here is the reason because of IIFE
    (function (css, id) {
      
    })(' ', 1);
})('' +
  ' <div>' +
  ' </div>' +
  '' + '');

also in css_parser , functionString trans

.a  .b{}

to

.a.b{}

Nesting components

Is it possible to nest components if I'm not using ES6. I have my define setup like this:

require.config({
    urlArgs: 'v=4.0-SNAPSHOT',
    baseUrl: '/static/js/',
    paths: {
        'Vue': 'lib/vue',
        'vue': 'lib/require-vuejs.min'
    },
    shim: {
        'Vue': {'exports': 'Vue'}
    }
});

define('browseView', ['Vue', 'vue!public/vueComponents/browseDisplay', 'vue!public/vueComponents/modalMetadata'], function(Vue){
    new Vue({
        el: '#browse_view'
    });
});

Then I'm using the modalMetadata component in the browseDisplay component, but I keep getting an error that modalMetadata isn't a valid component.

Thanks!

escape template

Hy,
Thanks your, good library
I found an error when the quotation marks are escaped

before
<img alt="" :src="photo.src + (photo.version || '')">

after
'' +
'<img alt="" :src="photo.src + (photo.version || \'')">' +
'' +

two single quotation escaped as \'' but must \'\'

Use plugin without referencing "template" variable.

It would be nice to not be required to reference the template variable in the component object. That would make .vue file definition more align with other loaders.

Some insights:

  1. With other loaders, .vue files should always export its definition as an object.
  2. If 1 is satisfied, we could execute the content of the script and inject template to returned value.

How to include css style when using r.js to combile the .vue files to one file?

Hi,

First thanks very much for this work. This helps me a lot.

In our project, we have style tag in .vue files, and we found our plugin not handle style code when using r.js to combile vue files to one file. (As below code)

    if(typeof document !== "undefined") {
            css_parser.parse(text);
        }

Do you know if there is an easy way to handle style code in this case?

Thanks a lot.

Nested templates parsing error

Hi,

When using require-vuejs on a vue component with nested templates such as here :

<template>
    <v-app>
        <Header pageName="Facturation"/>
        <sidebar :entity="entity" />
        <section>
            <h2>Historique de prélèvements</h2>
            <v-data-table
                    v-bind:headers="headers"
                    :items="readableArray"
                    hide-actions
                    class="elevation-1"
            >
                <template slot="items" scope="props">
                    <td>{{ props.item.label }}</td>
                    <td class="text-xs-right">{{ props.item.executionDate }}</td>
                    <td class="text-xs-right">{{ props.item.amount }}</td>
                </template>
            </v-data-table>
        </section>
    </v-app>
</template>

VueJS issues an error about v-data-table, section, v-app and template not having matching end tag.
It seems that template parsing ends at the first template end tag.

Uncaught TypeError: extractCss(...).replace is not a function

I get this error with this latest pluggin update, in case you can correct it as soon as possible that your work is very good and I am using it for a project right now. Thank you

"Uncaught TypeError: extractCss(...).replace is not a function"

Can not use word script in the component name

Hi.

I have following template:

<template>
  <scripts-finder></scripts-finder>
</template>

And this does not work with the plug-in. I did some debug and seems that script_parser.extractScript does not support that !

I'll make a pull request for that.

access my local html file by chrome

Dear, for help:
I access my local html by chrome,the require-vuejs can't actually access the file by loadRemote method(not the loadLocal method), throwing error "Uncaught Error: Load timeout for modules: vue!business/samples/dialog/Dialog_unnormalized5...", how can I figure this out?

No sources in chrome dev tools

Hi

I must be doing something very wrong but I cannot see the sources in the chrome dev tools. I can put a debugger statement into the code, which stops the debugger in the dev tools and then I can step through the files.

But that approach is inconvient. Is there some documentation how to approach developemnt?

Best regards

Case Sensitive Template

When using PascalCase components, and having the browse load the .vue files, all html tags are lower cased, and then vue can't load the right components.

scopped css

Hy,

Thanks for your work.
Scopped CSS doesn't seems to work

Regards

Cannot Compress with r.js

I'm having issues compressing r.js. It says Error: ReferenceError: document is not defined. I think the culprit is line 21 of plugin.js, since parse gets called regardless of where we are in build mode or in the browser

Nested components

Hello

Is it possible to require components in another component ?

   function displayItem(item) {
       $('.tab-item').hide();
       $('.' + item).show();
   }

   define(["Vue"], function (Vue) {         
         Vue.component("my-main", {
             template: template,
             methods: {
                 creation: () => displayItem('creation'),                  
                 missionner: () => displayItem('missionner')                  
             },
            components: {
                           "custcomp" : require(["vue!./Components/title.html"], function (t) { console.log(t)})
             },
             mounted: function () {
                 $(".tab-item").hide();
             }
         });
       });

Regards

Does not work with ES6-Promise polyfill

I am trying to use this plugin in IE11 (as part of developing a non-transpiled Excel add-in, which run in an IE11 frame when used with Office desktop), so I have to rely on a polyfill to make promises work. While no error is thrown, Vue eventually times out trying to load the component. Wondering if there is a simple fix for that and looking forward to being able to use this seemingly awesome plugin.

Uncaught TypeError: plugin.load is not a function

A difficult to reproduce error on the first require(["vue!" + path]); when the cdn of requirejs-vue takes too long to load but finally loads.

my require.config looks like this:

require.config({
    waitSeconds: 0,
    paths: {
        jquery: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery",
        Vue: "https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue",
        vue: 'https://cdn.rawgit.com/edgardleal/require-vuejs/aeaff6db/dist/require-vuejs',
        router: "../src/router/index"
    },
    shim: {
        router: ["jquery", "Vue", "vue"],
    }
});

require(['Vue'], function (vue2) {
    window.Vue = vue2;
});

require([
    "jquery",    
    "Vue",
    "vue",
    "router"
]);

Has anyone already had this issue?

Separating JS in separate files

Is it possible to separate the js into a separate file similar to how the Vue documentation does it?

For example:

<template>
  <div>This will be pre-compiled</div>
</template>
<script src="./my-component.js"></script>

Whenever I try it, the plugin doesn't incorporate the other js.

The resulting file ends up like this:

(function(template){
})('' + 
' <div>' + 
' This will be pre-compiled' + 
' </div>' + 
'' + '');

customize "vue!"

I found it slightly confusing when starting to use this library because the main app.js would require both Vue (the standard library) and vue (this project which is for requiring vue).

I was wondering if one may customize the name of "vue" to make it more obvious. For example, change:

  paths: {
    "Vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue",          //for dev
    "vue": "https://rawgit.com/edgardleal/require-vue/master/dist/require-vuejs",
  },

into:

  paths: {
    "Vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue",          //for dev
    "reqV": "https://rawgit.com/edgardleal/require-vue/master/dist/require-vuejs",
  },

So instead of using vue! you could use reqV!, if you prefer.

I tried this and it breaks require-vuejs. The error I see in my browser console:

require.js:968 Uncaught TypeError: Cannot read property 'normalize' of undefined
    at b.<anonymous> (require.js:968)
    at require.js:134
    at require.js:1189
    at each (require.js:59)
    at b.emit (require.js:1188)
    at b.check (require.js:938)
    at b.enable (require.js:1176)
    at b.init (require.js:788)
    at h (require.js:1203)
    at Object.completeLoad (require.js:1611)

Is there a reason why the name "vue!" shouldn't be customizable? Granite, I don't have much experience with require.js, and I don't know the "right" way to do things.

Tag for current master version

Hello, have you planning to create a tag for current master changes?
Currently the newest tag is 1.1.1 and then fix for Firefox came, but still with old tag.

Thanks!

template tag in template section is not supported

Example code:

<template>
	<div id="div2">
              <template>{{text}}</template>
        </div>
</template>

<script>
    define(["Vue"], function(Vue) {
		console.log(" registering the component my-component2");
		Vue.component("my-component2", {
			template: template,
			data: function() {
				return {"text": "Ok from component.html"};
			}
		});
    });
</script>

<style>

div#div2 {
	border: 1px solid red;
}
</style>

It will throw en error, that template and dev tags are not closed.

vue aliases in require-config

Is it possible to define aliases for vue components in require-config?

For example:

require-config:

paths: {
    'grid': 'ui/vue/grid'
}

main.js:

define(['vue!grid'], function (Grid){
Vue.component('grid', Grid);
...
})

Chrome DevTools debugging?

How can I debug the .vue or .html component file for the vue component? the files do not show up in the Sources tree view when using Chrome DevTools. I manually added it, but it doesn't stop on breakpoints.

Scoped slots triggers 'Error compiling template' warning

Vue.js has a scoped slots feature which allows you pass properties from your child components and access them from the parent. More info can be found here: https://vuejs.org/v2/guide/components.html#Scoped-Slots

According to the Vue documentation,

In the parent, a <template> element with a special attribute scope must exist, indicating that it is a template for a scoped slot. The value of scope is the name of a temporary variable that holds the props object passed from the child

Example:

    <div class="parent">
      <child>
        <template scope="props">
          <span>hello from parent</span>
          <span>{{ props.text }}</span>
        </template>
     </child>
    </div>

The problem arises when you use a custom component which uses scoped slots in a single-file component. It does not seem to like nested template tags and triggers a [Vue warn]: Error compiling template: error. Any ideas?

How to use router-vue.js

Hello,

I'm trying to use the router-vue but I have some problems to dynamically load the right component. Would you have any advice for me, please?

I have something that works without require-vue, I don't find how to import my vue file into my components routes !

`requirejs.config({
paths: {
"Vue": "./js/libraries/vue",
"vue": "./js/libraries/require-vuejs",
"VueRouter": "./js/libraries/vue-router"
},
shim: {
"Vue": {"exports": "Vue"}
}
});

require(["Vue", "VueRouter", 'vue!./components/test.vue', 'vue!./components/HelloWorld.vue'], function(Vue, VueRouter){

const router = new VueRouter({
							routes : [
								{
									path: '/',
									name: 'test',
									component:  { template: '<div>foo</div>', name: 'test'}
								},
								{
									path: '/hello',
									name: 'hello',
									component: { template: '<div>bar</div>', name: 'hello'}
								}
							]
						})

Vue.use(VueRouter);

const app = new Vue({
	router
}).$mount('#app');

});`

Thank you in advance

Docs: configuration for r.js

I executed:

r.js -o build.js

I have got an error:

Error: ENOENT: no such file or directory, open 'somefile.js'
In module tree:
    somemodule
      vue

Should I place vue in exclude or define with empty: in paths?
Neither of it works.

1.1.3 errors on large template file

I'm running into an issue where my vue template file is much longer than the others (x3) and the following line errors within the parse function:

var parse = function(text) {
        var doc = document.implementation.createHTMLDocument("");
        doc.body.innerHTML = text;
        var scriptElement = doc.getElementsByTagName("script")[0];
        var source = scriptElement.innerHTML;
        var css_result = css_parser.parseElement(doc);
        var template = template_parser.extractTemplate(doc, css_result);
        var functionString = css_result.functionString;
        if (!source || source.length < 10) {
            source = scriptElement.src;
            source = "define(['" + source + "'], function(comp) {\n comp.template = template;\n return comp;\n});\n";
        }

scriptElement is undefined. seems to work fine for my other vue templates, but this one it fails to find the script tag. This only happened once I upgraded to v 1.1.3. The template its erring on is 331kb. I'm guessing that a size limitation is happening and therefore it's truncating the template file not even loading the script block? Possibly the passed in "text" parameter?

2x times the same class name with modificator in <style>

Hi ! I found a bug with using a <style> in single file component. Let's check an example:

<style>
    .test {
        position: relative;
    }
    .test::after {
        content: '';
    }
</style>

Using 2x time the same style name (one time normal, 2nd time with modificator) return a following error

Error: fromText eval for vue!component failed: SyntaxError: missing ) after argument list

Can You check it ?

How to load component and render it dynamically

I'm trying to load a view component dynamically so when one clicks previous/next it loads the previous or next step component. if I list all the components in the requirejs define , it works, but I plan on having quite a few step components, so I'd rather load dynamically / on demand. I've done the following and requirejs does in fact load the vue template .html file when clicking the prev/next, but vue is not rendering the component. I got this far following: https://vuejs.org/v2/guide/components.html#Dynamic-Components mainly. I was also looking at comment #23 (comment), and changing how the vue .html files were setup, but still not getting it to work.

I'm guessing I'm missing how to get Vue to re-render the component or something similar. Any help is appreciated. here's some psuedo-code, sorry for not having a usable example yet. Any help is most appreciated.

<div>
    <keep-alive>
        <component :is="stepComponent" :key="componentKey"></component>                   
    </keep-alive> 
</div> 

example component


<template>
    <div id="stepComponent"> 
        <p class="font-larger green">Step Two!</p>
    </div>
</template>
<script>
    define(['Vue'], function (Vue) {
        var component = {            
            template: template,
            props: {
            },
            data: function () {
                return {
                }
            }, created() {
            }
            , methods: {
            }
            , computed: {}
        };
        Vue.component("enroll-step-two", component);
        return component;        
    });
</script>
var VM= new Vue({
       el: '#sectionContent',
       components: {
           'step-one': () => require(['vue!_assets/components/step-one.html']),
           'step-two': () => require(['vue!_assets/components/step-two.html'])
       },
       
       created() {
        
       }
       , mounted() {
        
       }
       , data: {
           steps: [{ id: 1, title: 'Step One', template: 'step-one', ref: 'stepOne', isLoaded: false }, { id: 2, title: 'Step Two', template: 'step-two', ref: 'stepTwo', isLoaded: false }], 
           step: 1,           
           enrollment: {},
           componentKey: 0            
       }
       , methods: {            
           prev() {
               if (this.step > 0) {
                   this.step--;
                
               }
           },
           next() {
               if (this.step, this.steps.length) {
                   this.step++; 
                
               }
           }
       } // methods      
       , computed: {                     
           stepComponent() {                 
               var comptemplate = this.steps[this.step - 1].template + '.html';
               var name = this.steps[this.step - 1].template;  
               this.componentKey++;
               return name;                                   
           }            
       } // computed      

   });//vue

How to call the router in component?

Hello,

In my component I need to call the Router, like that:

router.push({name:'dashboard'}).

How can I get the object "router" initialized before in the file app.js in my component?

Thank you.

Is it possible to use a inner template within a template?

It is possible to use v-if with in .
( </ template>) There is a problem that the tag after the inner template does not render normally.

I modified some code on the component to reproduce the phenomenon

<template>
    <div>
        <h1> {{text}} </h1>

        <template v-if="true">
            <div> Inner template</div>
        </template>

        <div>It is not shown</div>
    </div>
</template>

Finally love your work!

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.