The following HTML code
<!DOCTYPE html>
<html lang="en">
<body>
Greeting below:
<div id="time">
{{greetings}}
</div>
<script src='bundle.js'></script>
</body>
</html>
together with the entry.js
file
// either the import or the require work
Vue = require('./vue.js')
//import Vue from './vue.js'
new Vue({
el: "#time",
data: {
greetings: "hello world"
}
})
and the webpack.config.js
module.exports = {
entry: './entry.js',
output: {
filename: 'bundle.js'
}
}
works fine (vue.js
is locally downloaded from the site or a CDN).
I then tried to use the vue
module installed via npm install vue --save-dev
by changing entry.js
to
import Vue from 'vue'
new Vue({
el: "#time",
data: {
greetings: "hello world"
}
})
This version does not work anymore: the whole <div>
is not rendered (only Greeting below
is displayed).
What should be done so that Vue.js can be used with webpack?
The Vue documentation mentions webpack a few times, but only in the context of components or production builds.
To diagnose the problem it's a good idea to look for any errors, whether it's from the build tool on the command line or in the devtools in the browser. If you open the devtools console you'll see the following warning from Vue:
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
Vue has a two different builds, Runtime + Compiler vs. Runtime-only. If you have templates in the DOM, they need to be compiled in order to use them. By default Vue contains only the runtime, because its more light-weight and usually the templates are already pre-compiled to JavaScript at build time.
To also include the compiler you need to import vue/dist/vue.esm
:
import Vue from 'vue/dist/vue.esm'
This is the same version as the one from the CDN, except that it uses ES modules, which webpack will handle and you should prefer it over vue/dist/vue.js
, which is exactly the one from the CDN.
Alternatively you can use webpacks resolve.alias
to define an alias, so when you import vue
it will import vue/dist/vue.esm
instead.
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
}
To be able to use the runtime-only build, you can use Single File Components with a .vue
file. For that you will have to configure vue-loader
, which will pre-compile the templates at build time.