问题 如何在不使用vue-cli的情况下使用vue-loader


我正在尝试将使用webpack转换.vue文件的Vue项目的绝对最低限的示例放在一起。

我的目标是详细了解每个构建步骤。大多数教程都建议使用 vue-cli 并使用 webpack-simple 配置。尽管这种设置有效,但对我的简单目的而言似乎有些过分。现在我不想要使用热模块重新加载的babel,linting或实时Web服务器。

一个简单的例子 import Vue from 'vue' 作品! Webpack将vue库和我自己的代码编译成一个包。

但现在,我想补充一下 VUE装载机 到webpack配置,这样 .vue 文件将被翻译。我已经安装了vue loader:

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

我已经在webpack配置中添加了vue-loader:

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!")
      }
    })

装载机似乎没有拿起 .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组件?


6133
2017-09-29 16:56


起源

你能加错吗? - imcvampire
你在哪里真正尝试导入 .vue 文件?是的,请分享你得到的错误。 - thanksd
当我尝试时,我已经编辑了这个问题 import .vue文件中的代码找不到此代码。 - Kokodoko


答案:


首先,您没有正确导入文件。您应该像这样导入它:

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']
}

这是关于的文档 resolve.extensions


10
2017-09-29 17:23



非常感谢,我错过了注册组件 Vue.component('hello', Hello),现在它开始有意义了...... :) - Kokodoko


除了@thanksd回答:

从vue-loader v15开始,需要一个插件:

// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  module: {
    rules: [
      // ... other rules
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]
  },
  plugins: [
    // make sure to include the plugin!
    new VueLoaderPlugin()
  ]
}

https://vue-loader.vuejs.org/guide/


1
2018-05-10 20:06





在这里标记更多信息以及@lukebearden和@thanksd。从头开始设置一个Vue应用程序,它是基本的,我在这个过程中撕掉了一些样式,因为我不想处理它:但是它编译了JS:

https://github.com/ed42311/gu-vue-app

可以确认插件,我还没有添加决心,但现在我会:)

如果您有任何想法,请告诉我。


0
2017-07-19 13:27