我试图将使用webpack转换.vue文件的Vue项目的绝对最低限的例子放在一起.
我的目标是详细了解每个构建步骤.大多数教程建议使用vue-cli和使用webpack-simple配置.尽管这种设置有效,但对我的简单目的而言似乎有些过分.现在我不想要使用热模块重新加载的babel,linting或实时Web服务器.
一个最小的例子,只是import Vue from 'vue'工作!Webpack将vue库和我自己的代码编译成一个包.
但现在,我想将vue-loader添加到webpack配置中,以便将.vue文件转换成文件.我已经安装了vue loader:
npm install vue-loader
npm install css-loader
npm install vue-template-compiler
Run Code Online (Sandbox Code Playgroud)
我已经在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'
}
}
};
Run Code Online (Sandbox Code Playgroud)
我创建了hello.vue
<template>
<p>{{greeting}} World</p>
</template>
<script>
export default {
data:function(){
return {
greeting:"Hi there"
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
在我的应用程序中,我导入'你好'
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!")
}
})
Run Code Online (Sandbox Code Playgroud)
加载器似乎没有拿起.vue文件,我收到错误:
Module not found: Error: Can't resolve './hello.js'
Run Code Online (Sandbox Code Playgroud)
编辑
当import hello from 'hello.vue'我试图得到错误时:
Unknown custom element: <hello> - did you register the component correctly?
Run Code Online (Sandbox Code Playgroud)
我错过了一步吗?我是否以正确的方式导入.vue组件?如何使用app.js中的hello.vue组件?
tha*_*ksd 15
首先,您没有正确导入文件.您应该像这样导入它:
import Hello from './hello.vue'
Run Code Online (Sandbox Code Playgroud)
其次,导入组件后,您仍需要以某种方式注册它.要么全局执行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!")
}
})
Run Code Online (Sandbox Code Playgroud)
作为旁注,如果您希望能够导入文件而不必指定.vue扩展名,则可以指定.vue应在配置文件中解析扩展名.
在这种情况下,resolve配置文件中的对象应如下所示:
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['.js', '.vue', '.json']
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7030 次 |
| 最近记录: |