美文网首页前端
从零开始搭建一个基于webpack的Vue开发环境(3)

从零开始搭建一个基于webpack的Vue开发环境(3)

作者: zshawk1982 | 来源:发表于2019-12-20 12:50 被阅读0次

    经历了前两部分的操作,相信各位也明白了webpack打包项目的基本使用,这样就不用拘泥于vueCli,自己也可以很好的打包,同时对底层理解也会更深。
    好了,到了第三部分,我们需要做以下几件事:
    1.使用vue单文件组件
    2.使用splitcode,拆分代码
    3.开启sourcemap,便于调试
    4.开启webpack的HMR
    同样,我们先看下目录结构


    项目结构

    我们先来看下package.json中新增的

    {
      "name": "webpack_demo2",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack",
        "dev": "webpack-dev-server"
      },
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "@babel/core": "^7.6.0",
        "@babel/plugin-transform-runtime": "^7.6.0",
        "@babel/preset-env": "^7.6.0",
        "@babel/runtime-corejs3": "^7.6.0",
        "babel-loader": "^8.0.6",
        "clean-webpack-plugin": "^3.0.0",
        "css-loader": "^3.2.0",
        "file-loader": "^4.2.0",
        "html-webpack-plugin": "^3.2.0",
        "node-sass": "^4.12.0",
        "sass-loader": "^8.0.0",
        "style-loader": "^1.0.0",
        "vue-loader": "^15.7.1",
        "vue-style-loader": "^4.1.2",
        "vue-template-compiler": "^2.6.10",
        "webpack": "^4.39.3",
        "webpack-bundle-analyzer": "^3.4.1",
        "webpack-cli": "^3.3.7",
        "webpack-dev-server": "^3.8.0"
      },
      "dependencies": {
        "vue": "^2.6.10"
      }
    }
    
    

    我们新安装了

    npm install --save-dev vue-loader
    npm install --save-dev vue-template-compiler
    npm install --save-dev webpack-bundle-analyzer
    

    这里vue-loader和vue-template-compiler用于针对vue单文件组件的编译,webpack-bundle-analyzer则是用于帮助我们查看代码分割的效果的一个插件
    接着我们来看util.js,做了点点修改,写了两个异步获取数据的方法

    function getData() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("hello vue")
        }, 2000)
      })
    }
    
    function getData2() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("hello vue2")
        }, 2000)
      })
    }
    
    export { getData, getData2 }
    

    然后是main.js文件的内容:这里我们引入了App.vue这个单文件组件

    import Vue from 'vue'
    import './css/main.scss'
    import { getData } from './util'
    import loginJpg from './img/login-bg.jpg'
    import App from './App.vue'
    new Vue({
      el: '#app',
      data: {
        content: 'hello world',
        loginJpg: loginJpg
        // loginJpg2: require('./img/login-bg.jpg')
      },
      template: `
        <div class="main">
        {{content}}
        <App></App>
        <img :src="loginJpg"/>
        </div>
      `,
      components: {
        App
      },
      methods: {
        async fetchData() {
          this.content = await getData()
        }
      },
      created() {
        this.fetchData()
      }
    })
    

    之后我们来看下App.vue的内容:

    <template>
      <div class="app">
        <h1>{{ msg }}</h1>
        <img src="./img/img.jpg">
        <input type="text"
               v-model="msg">
      </div>
    </template>
    
    <script>
    import { getData2 } from './util'
    
    export default {
      name: 'App',
      data() {
        return {
          msg: 'Welcome to Your Vue.js'
        }
      },
      mounted() {
        this.fetchData()
      },
      methods: {
        async fetchData() {
          try {
            const data = await getData2()
            this.msg = data
    
          } catch (e) {
            console.log('错误是', e)
          }
        }
      }
    }
    </script>
    
    <style lang="scss">
    .app {
      font-family: "Avenir", Helvetica, Arial, sans-serif;
    
      h1 {
        color: green;
      }
    }
    </style>
    

    最后是我们的webpack配置文件:

    const path = require('path')
    const webpack = require('webpack')
    const HtmlWebpackPlugin = require('html-webpack-plugin')
    const { CleanWebpackPlugin } = require('clean-webpack-plugin')
    //使用vue-loader也必须引入VueLoaderPlugin这个插件
    const VueLoaderPlugin = require('vue-loader/lib/plugin')
    //使用webpack-bundle-analyzer做代码分析,需要引入这个插件
    const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
    
    module.exports = {
      entry: {
        //设置两个入口
        app: './src/main.js',
        vendor: ['vue']
      },
      output: {
        path: path.resolve(__dirname, 'dist'),
        //两个打包文件,一个app.js,一个vendor.js
        filename: '[name].js',
        //output的publicPath决定了异步加载的js,使用htmlWebpackPlugin插入的bundle.js,从css中引入的图片或字体,以及miniCssExtractPlugin分离的css等的文件引用路径
        publicPath: '/dist/'
      },
      //设置js的sourcemap
      devtool: 'source-map',
      mode: 'development',
    
      optimization: {
        //设置js压缩
        // minimize: true,
        //设置codespliting提取公共部分
        splitChunks: {
          chunks: 'all'
        }
      },
      devServer: {
        publicPath: "/dist/",
        //开启hmr
        hot: true
      },
      module: {
        rules: [
          // {
          //   //css样式被bundle.js注入到html页面的style里
          //   test: /\.css$/i,
          //   exclude: /node_modules/,
          //   use: ['style-loader', 'css-loader']
          // },
          {
            //提供es6语法支持,使得await,async,promise在任何浏览器可用
            test: /\.js$/i,
            exclude: /node_modules/,
            use: ['babel-loader']
          },
          {
            test: /\.scss$/i,
            exclude: /node_modules/,
            use: ['vue-style-loader',
              {
                loader: 'css-loader',
                options: {
                  //css-loader和sass-loader的sourcemap都要设置,才会生效
                  sourceMap: true
                }
              },
              {
                loader: 'sass-loader',
                options: {
                  //css-loader和sass-loader的sourcemap都要设置,才会生效
                  sourceMap: true
                }
              }]
          },
          {
            test: /\.vue$/,
            loader: 'vue-loader'
          },
          {
            test: /\.(png|jpe?g|gif)$/i,
            use: [
              {
                loader: 'file-loader',
                options: {
                  name: '[name].[ext]',
                  outputPath: './images/',
                  // publicPath: './images2/'
                }
              },
            ],
          },
        ]
      },
      plugins: [
        //在custom下以template.html为模板生成index.html文件,同时将
        //[name].js插入html文件的body底部
        new HtmlWebpackPlugin({
          template: './template.html',
          filename: 'index.html'
        }),
        //该插件用于每次build之前自动清除dist目录
        new CleanWebpackPlugin(),
        //vueload还需要这个插件才可以生效
        new VueLoaderPlugin(),
        //打包分析插件,会生成html图表
        new BundleAnalyzerPlugin(),
        //HMR的插件(HMR只能webpack-dev-server下使用)
        new webpack.HotModuleReplacementPlugin()
      ],
      resolve: {
        alias: {
          //指定采用编译环境的vue
          'vue$': 'vue/dist/vue.esm.js'
        }
      }
    }
    

    第二点

    我们设置了两个入口,一个是app,一个是vendor,vendor用于指定node_module中vue,意思是vue作为一个单独的入口,这是我们用webpack-bundle-analyzer插件查看:


    里面有两个vue,每个入口都会产生一个vue

    这里我们使用webpack4的splitChunks,就实现了公共代码的提取,这里的vue就是两个入口都有的公共代码,所以被提取了处理,如下图所示:


    vue的代码被提取出来了

    第三点

    公共代码提取,我们已经完成了,下面我们为了方便js调试和css调试
    我们设置了devtool: 'source-map',该项用于js调试,不然js显示的都是webpack处理后的代码,我们就没法区分出自己的了
    在然后是在css-loader和sass-loader分别设置sourceMap: true只有两处都设置了,最后的css代码我们才可以调试.

    第四点

    第三点完成了,我们完成第四点,也就是开启webpack的hmr,hmr是为了方便webpack-dev-server的,有了hmr就不用每次都live-reload了(live-reload就是当更新源码时,webpack-dev-server会都自动刷新页面)而是会自动局部更新修改的内容(live-reload的缺点在于刷新页面也许会让页面丢失状态,而hmr局部更新则不会)
    开启hmr很简单,在plugin中设置new webpack.HotModuleReplacementPlugin(),然后在devServer中指定hot: true

    相关文章

      网友评论

        本文标题:从零开始搭建一个基于webpack的Vue开发环境(3)

        本文链接:https://www.haomeiwen.com/subject/djtgyctx.html