Hamed Kamrava
Hamed Kamrava

Reputation: 12847

How to import a component in Vuejs 2

I'm really confused about importing a VueJs component.

I'm using Vuejs 2.2.4, and I need to import a Vuejs component. Here is my app.js:

Vue.component('Test', require('./Test.vue'));

const app = new Vue({
    el: '#vue-app',
});

Assume app.js is located in MyProject/js/app.js

And here is my component SimpleCompnent.vue :

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Simple Component</div>
                    <div class="panel-body">
                        I'm an Simple component!
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Simple Component mounted.')
        }
    }
</script>

Assume SimpleCompnent.vue is located in MyProject/js/SimpleCompnent.vue

Seems like Vue can't load the component! It throws this error in the browser console:

Uncaught ReferenceError: require is not defined

Upvotes: 2

Views: 14623

Answers (2)

Saurabh
Saurabh

Reputation: 73589

Try:

import Test from './Test.vue'

You can see an example of it here.

Upvotes: 3

Eliran Malka
Eliran Malka

Reputation: 16263

Indeed, require cannot be used in a browser context without proper support, so you have couple of options:

  • Create (or fix) support for require.js in your app (see how here). As a first step, make sure you have a script tag that fetches require.js and has a data-main attribute that points to your app's entrypoint.

  • Use a CommonJS implementation for the client, like webpack or browserify, so requires can be written naturally in client-side code.

  • Use another module system implementation, e.g. on top of system.js or ES2015.

Either way, if you chose an implementation that uses imports (i.e. an ES2015 module system), you may want to use a transpiler that down-compiles your code to a language level the browser supports (avoiding those nasty Unexpected token import errors).

Upvotes: 3

Related Questions