2017-09-29 79 views
6

我正在嘗試使用webpack來轉譯.vue文件的Vue項目的絕對最小示例。如何使用vue-loader而不使用vue-cli

我的目標是詳細瞭解每個構建步驟。大多數教程建議使用vue-cli並使用webpack-simple配置。儘管這個設置起作用,但爲了我的簡單目的,這看起來過分了。現在我不想讓babel,linting或者帶有熱模塊重載的live web服務器。

一個簡單的例子,只有import Vue from 'vue'工程! Webpack將vue庫和我自己的代碼編譯成一個包。

但是現在,我想將vue-loader添加到webpack配置中,以便.vue文件將被轉發。我已經安裝了VUE裝載機:

npm install vue-loader 
npm install css-loader 
npm install vue-template-compiler 

而且我已經加入VUE裝載機到的WebPack配置:

var path = require('path') 

module.exports = { 
    entry: './dev/app.js', 
    output: { 
    filename: 'bundle.js', 
    path: path.resolve(__dirname, 'dist') 
    }, 
    module: { 
    rules: [ 
     { 
     test: /\.vue$/, 
     loader: 'vue-loader', 
     options: { 
      loaders: { 
      } 
     } 
     } 
    ] 
    }, 
    resolve: { 
    alias: { 
     'vue$': 'vue/dist/vue.esm.js' 
    } 
    } 
}; 

我創建hello.vue

<template> 
    <p>{{greeting}} World</p> 
</template> 

<script> 
export default { 
    data:function(){ 
     return { 
      greeting:"Hi there" 
     } 
    } 
} 
</script> 

而且在我的應用我進口'你好'

import Vue from 'vue' 
import hello from "./hello.vue"; 

    new Vue({ 
     el: '#app', 
     template:`<div><hello></hello></div>`, 
     created: function() { 
     console.log("Hey, a vue app!") 
     } 
    }) 

Th Ë裝載機似乎沒有拿起.vue文件,我得到的錯誤:

Module not found: Error: Can't resolve './hello.js' 

編輯

當試圖import hello from 'hello.vue'我得到的錯誤:

Unknown custom element: <hello> - did you register the component correctly? 

我錯過一步?我是否正確導入.vue組件?如何使用app.js中的hello.vue組件?

+0

你能添加錯誤? – imcvampire

+0

你究竟在哪裏試圖導入'.vue'文件?是的,請分享您遇到的錯誤。 – thanksd

+0

我已經編輯了這個問題,當我嘗試從「導入」代碼。vue文件未找到此代碼。 – Kokodoko

回答

5

首先,您沒有正確導入文件。你應該像這樣導入它:

import Hello from './hello.vue' 

其次,在你導入組件後,你仍然需要以某種方式註冊它。無論是做全球Vue.component('hello', Hello),或在Vue公司的實例:

new Vue({ 
    el: '#app', 
    template:`<div><hello></hello></div>`, 
    components: { 'hello': Hello }, 
    created: function() { 
    console.log("Hey, a vue app!") 
    } 
}) 

作爲一個側面說明,如果你希望能夠導入的文件,而無需指定.vue擴展,你可以指定.vue擴展應該在您的配置文件中解決。

在這種情況下,resolve對象在你的配置文件應該是這樣的:

resolve: { 
    alias: { 
    'vue$': 'vue/dist/vue.esm.js' 
    }, 
    extensions: ['.js', '.vue', '.json'] 
} 

Here's the documentation on resolve.extensions.

+0

非常感謝,我錯過了用'Vue.component('hello',Hello)'註冊組件,現在它開始有意義了...... :) – Kokodoko