Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require Vue from JS file

i'm pretty new to modern frontend development tools. I installed Nodejs and NPM. Downloaded some packages (es: "jquery") and everything worked. Then I installed Webpack (vers. 2), I created this demo config file

module.exports = {
   entry: "./entry.js",
   output: {
       path: __dirname,
       filename: "bundle.js"
   }
};

In my JS entry point (entry.js) I can successfully use jQuery module, as follows

var $ = require("jquery");
$('#test').html('Changed!');

Everything works fine. The problem arises when I go for Vue. I install it

npm install vue --save

And then use it

var Vue = require("vue");
var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    }
});

I don't know how to import and then use the constructor. What I wrote clearly cannot be right! In fact I get this error

TypeError: Vue is not a constructor

What am I missing? (NOTE: I am not using any other tool, only Nodejs + NPM + Webpack2 and I would like to keep going using only these three, if possibile).

Thank you, Marco

like image 470
Marco Avatar asked Mar 15 '17 11:03

Marco


People also ask

How do I import a JavaScript file into Vue?

Here, you can import the JavaScript library by using the 'import' keyword inside the script tag of your Vue file. import * as mykey from '../assets/js/mykey. js'; The second way is to include your external JavaScript file into the mounted hook of your Vue component.

Is a Vue file a js file?

. vue files aren't plain JavaScript, but you can get some JS your browser can work with by transpiling it. With webpack in place, now you can use . vue files, and better organize your code for building more complex web apps.

How do you link Vue js file to HTML?

The simplest way to get started with Vue is to grab the development version script for it and add it to the head tag of your HTML file. Then you can start Vue code inside the HTML file inside of script tags. And have the Vue code connect up with an existing element on your HTML page.

How do I save a Vue js file?

In your text editor, open the src/main. js file. Once you've chained the use method, save this file. The use method tells the Vue application which code to bundle together when the application is built.


1 Answers

Vue provides an ES module that is used by webpack. The constructor you expected is the default export, but require works a little differently so you need to access the default property on the import.

var Vue = require('vue').default;

Or you can use the import syntax which is supported by webpack. The equivalent import is:

import Vue from 'vue';
like image 167
Michael Jungo Avatar answered Oct 05 '22 22:10

Michael Jungo