Require Vue from JS file

ぐ巨炮叔叔 提交于 2019-12-12 10:43:59

问题


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


回答1:


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';


来源:https://stackoverflow.com/questions/42808261/require-vue-from-js-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!