从0开始Vue.js 和 Webpack 4 [2]

时间:2022-06-09
本文章向大家介绍从0开始Vue.js 和 Webpack 4 [2],主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

核心目标

  • 使用webpack-dev-server热加载模块
  • 使用eslint文件瘦身
  • 使用stylus进行CSS预处理
  • 使用@ vue / test-utils和Jest进行测试

webpack其他服务

安装webpack-dev-server自动加载修改内容

npm install --save-dev webpack-dev-server

package.json加入入口命令

./package.json

"dev": "webpack-dev-server --config build/webpack.config.dev.js"

但是此时如果更改App.vue文件内容,页面并不会实时改变。

原因:当配置index.html时,指定了javascript的具体路径,为了使热模块重新加载工作,需要允许注入此路径,这样就可以实时更新html了。

./index.html

删除<script src="dist/main.js" type="text/javascript"></script>

安装html-webpack-plugin

npm install --save-dev html-webpack-plugin

./build/webpack.config.dev.js

'use strict'
const webpack = require('webpack')
const { VueLoaderPlugin } = require('vue-loader')
//引入html-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
  mode: 'development',
  
  entry: [
    './src/app.js'
  ],
  //热加载配置
  devServer: {
    hot: true,
    watchOptions: {
      poll: true
    }
  },
  module: {
    rules: [
      {
        test: /.vue$/,
        use: 'vue-loader'
      }
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
        //文件注入位置
      filename: 'index.html',
      template: 'index.html',
      inject: true
    })
  ]
}

vue模块测试

./components/HelloComponent.vue

<template>
  <h1>Hello {{ name }}!</h1>
</template>
<script>
export default {
  props: {
    name: {
      type: String,
      required: true
    }
  }
}
</script>
<style >
h1{color:red}
</style>

./src/App.vue

<template>
  <div class="full-width center-content">
    <hello-component name="World" />
  </div>
</template>
<script>
import HelloComponent from './components/HelloComponent.vue'
export default {
  components: {
    HelloComponent
  }
}
</script>

安装Babel,将ES6代码转换为ES5,兼容所有浏览器

npm install --save-dev babel-core babel-loader babel-preset-env

./build/webpack.config.dev.js

{
  test: /.js$/,
  use: 'babel-loader'
}

./.babelrc

{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }]
  ]
}