用webpack4搭一个vue项目

平时一般都用vue-cli,今天自己来手动搭一个vue项目,当然基本项目结构还是参考vue-cli的。

引入vue包错误

在js文件中直接 import Vue from 'vue' 导入vue之后使用可能会报一下错误

webpack You are using the runtime-only build of Vue where the template compiler is not available...

这是因为node_modules目录下vue目录下package.json中 

实际上我们想引的是vue.js

解决办法:可以在webpack.config.js文件中加入一个别名配置

//与plugins、module同级
resolve: {
    alias: {
         vue: 'vue/dist/vue.js'
    }
}

使用.vue文件

需要使用 vue-loader 解析处理.vue文件,vue-loader依赖 vue-template-compiler

npm install vue-loader vue-template-compiler --save-dev

一贯套路在webpack.config.js中加入一个loader规则

{
     test: /\.vue$/,
     use: ['vue-loader']
}

注意:如果就这样直接还是会报错,因为Vue-loader在15.*之后的版本都是 vue-loader的使用都是需要伴生 VueLoaderPlugin的

所以还应该在webpack.config.js中加入插件

const VueLoaderPlugin = require('vue-loader/lib/plugin');
...
...
plugins: [
     new VueLoaderPlugin()
]

至此就可以在项目中正常使用.vue文件了

省略文件扩展名

在resolve配置中加一条

//与plugins、module同级
resolve: {
    extensions: ['.js', '.vue', '.json'],//后缀是.js .vue .json的可以省略后缀
    ...
}

路由

装包vue-router

npm install vue-router --save

src目录下创建router目录,router目录下新建index.js文件,index.js内容:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../pages/home.vue';    //这是写好的一个组件
// 安装路由
Vue.use(VueRouter);

export default new VueRouter({
    routes: [
        {path: '/', redirect: '/home'},
        {
            path: '/home',
            component: Home
        }
    ]
})

然后在main.js中引入然后挂载到vue实例中即可

import router from './router';

new Vue({
    el: '#app',
    router,
    ...
})
发布了63 篇原创文章 · 获赞 18 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/samfung09/article/details/86694444