综合 |webpack从零开始搭建vue项目并结合vuex

初始化并安装相关包

mkdir vuexpack
cd vuexpack
npm init

npm install --save-dev webpack webpack-cli
npm install --save-dev vue vuex
npm install --save-dev vue-loader vue-template-compiler//解析vue

//插件
npm install --save-dev clean-webpack-plugin//每次打包清空dist

配置

  1. 创建webpack.config.js
var VueLoaderPlugin = require('vue-loader/lib/plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry: {
        main:'./main.js'
    },
    plugins: [  
      new VueLoaderPlugin(),
      new CleanWebpackPlugin(),
    ],
    module: {  
        rules: [
            { test: /\.vue$/, use: 'vue-loader' }
        ]
    },
    output: {
      filename: '[name].js'
    },
    mode:'development'
};
  1. 入口文件main.js
//main.js
import View from './View.vue'
import Vue from 'vue';
import store from './store'
new Vue({
    el:"#app",
    store, //注入store
    render: c => c(View),//渲染子组件
})
  1. 子组件
//View.vue
<template>
    <div>{{count}}</div>
</template>

<script>
export default {
    computed: {
    count () {
      return this.$store.state.count
    }
  }
}
</script>
  1. store
//store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)

export default new Vuex.Store({
    state:{
        count:3
    }
})
  1. 展示页
//index.html
<body>
    <div id="app"></div>
    <script src="./dist/main.js"></script>
</body>
  1. 其他配置
//pakage.json
"scripts": {
    "build": "webpack"
},

打包

npm run build

打包后完整目录,现在index.html就能成功展示了!
image.png

posted @ 2020-09-01 14:19  sanhuamao  阅读(197)  评论(0编辑  收藏  举报