Sping Boot + Vue + Webpack 项目实战(三):配置静态资源、代码校验和webpack-dev-server

我只是一个虾纸丫 提交于 2020-03-12 08:41:57

前言

好了,上一篇我讲了怎么使用webpack来构建vue项目,接下将对它进一步完善,添加静态资源和代码校验及webpack-dev-server服务器,废话不多说,直接开始吧。

配置静态资源

安装

在配置之前,需要安装样式和文件资源处理的loader

npm install style-loader --save-dev
npm install --save-dev url-loader file-loader //url-loader是基于file-loader的
配置
module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.(gif|jpg|jpeg|png|svg)/,
                use: {
                    loader: 'url-loader',
                    options: {
                        limit: 1024,    // 每次输出文件的字节数的大小
                        name: '[name].[ext]'    // 输出的文件类型
                    }
                }
            }
        ]
    },

css处理器

这里css处理器使用的是stylus,当然也可以使用其他处理器,可以根据个人习惯去更换,我这里使用它是因为它编写的样式简洁,容易阅读

安装
npm install stylus-loader stylus --save-dev
配置
module: {
        rules: [
            {
                test: /\.styl(us)?/,
                use: [
                    'css-loader',
                    'stylus-loader'
                ]
            }
        ]
}

安装配置webpack-dev-server

安装
npm install --save-dev webpack-dev-server html-webpack-plugin	

npm install --save-dev cross-env
// cross-env是设置系统环境变量的,不同平台会有不同的环境变量,cross-env主要提供处理环境变量方案,只要正确的设置,则无需在开发中过多的去关注环境变量的设置问题
cross-env的配置

cross-env是运行跨平台设置和使用环境变量的脚本

{
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  }
}
webpack-dev-server的配置
const webpack = require('webpack')

const isDev = process.env.NODE_ENV === 'development'

const config = {
  target: 'web',  // 编译目标
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: isDev ? '"development"' : '"production"'
      }
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'template.html')
    })
  ]
}

if (isDev) {
    config.devtool = '#cheap-module-eval-source-map'
    config.devServer = {
        port: 8010,
        host: '0.0.0.0',    // 可以通过loaclhost、127.0.0.1、本机内网ip、手机等访问
        overlay: {  // 将编译的错误显示到页面上
            errors: true
        },
        hot: true   // 热加载
    }
}

html-webpack-plugin参看文档:https://www.webpackjs.com/plugins/html-webpack-plugin/

package.json 项目运行命令配置
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js",
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.js"
  },
// 运行命令
npm run dev

在这里插入图片描述

好了,到现在我们的项目算是构建和运行成功了,下面我们就来添加校验代码功能,为什么要添加代码校验,这里就不多说了,添加它可以更好的去管理代码,团队协作

代码校验eslint的配置

eslint官方文档:http://eslint.cn/docs

安装eslint
npm install --save-dev eslint
安装standard标准
npm install --save-dev eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node

在根目录下创建 .eslintrc 文件,到了这里是不是可以进行配置了呢,当然是可以的,但是eslint无法直接识别vue文件,所以还需要安装eslint-plugin-html

npm install --save-dev eslint-plugin-html
// 安装eslint对vue的校验
npm install eslint-plugin-vue --save-dev
.eslintrc文件配置
{
  "extends": ["standard", "plugin:vue/recommended"],
  "plugins": [
    "html"
  ]
}

运行eslint的命令配置(package.json)

  "scripts": {
    "lint": "eslint --ext .js --ext .jsx --ext .vue src/",
    "lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/"
  },

–fix自动修复问题代码

自动校验代码
npm i --save-dev eslint-loader babel-eslint

在eslintrc文件中增加如下配置

  "parserOptions": {
    "parser": "babel-eslint",
    "ecmaFeatures": {
      "jsx": true
    }

为了更好使用代码规则,避免错误的代码格式提交到远程仓库,需要安装husky(二哈)

npm i --save-dev husky

在package.json中的配置

 "scripts": {
    "lint-fix": "eslint --fix --ext .js --ext .jsx --ext .vue src/",
    "precommit": "npm run lint-fix"
  },

在正式开发项目功能之前还需配置postcss、babel

npm i --save-dev postcss-loader autoprefixer
npm i --save-dev babel-loader @babel/core

babel相关工具

npm i --save-dev @babel/preset-env babel-plugin-transform-vue-jsx @babel/plugin-syntax-jsx vue-eslint-parser babel-helper-vue-jsx-merge-props

postcss.config.js 配置文件

const autoprefixer = require('autoprefixer')

module.exports = {
  plugins: [
    autoprefixer()
  ]
}
module: {
        rules: [
            {
              test: /\.jsx$/,
              exclude: /(node_modules|bower_components)/,
              use: {
                loader: 'babel-loader',
                options: {
                  presets: ['@babel/preset-env']
                }
              }
            },
            {
                test: /\.styl(us)?/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                      loader: 'postcss-loader',
                      options: {
                        sourceMap: true
                      }
                    },
                    'stylus-loader'
                ]
            }
        ]
    }

.babelrc配置文件

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    "transform-vue-jsx"
  ]
}
CSS样式提取

安装

npm i --save-dev mini-css-extract-plugin

配置

 plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css'
    })
  ],
  optimization: {
    splitChunks: {
      cacheGroups: { // 设置缓存组
        commons: {
          chunks: 'initial',
          minChunks: 2, // 在分割模块之前共享模块的最小块数(默认是1)
          maxInitialRequests: 5, // 入口点上的最大并行请求数(默认是3)
          minSize: 0
        },
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          chunks: 'initial',
          name: 'vendor',
          priority: 10,
          enforce: true
        }
      }
    },
    runtimeChunk: true
  }

为了更好的管理webpack.config.js文件,我将它拆分成两个文件webpack.config.base.js和webpack.config.client.js,在拆分前,需要安装webpack-merge

npm i --save-dev webpack-merge

webpack.config.base.js

const path = require('path')

const config = {
  entry: path.resolve(__dirname, '../src/index.js'), // 入口js文件
  output: { // webpack打包输出js文件的路径及文件名
    filename: 'bundle.[hash:8].js',
    path: path.resolve(__dirname, '../dist')
  },
  mode: process.env.NODE_ENV || 'production', // 判断其环境
  module: {
    rules: [
      { // 代码校验
        test: /\.(vue|js|jsx)$/,
        loader: 'eslint-loader',
        exclude: /node_modules/,
        enforce: 'pre'
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.jsx$/,
        loader: 'babel-loader'
      },
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: ['@babel/transform-runtime']
          }
        }
      },
      {
        test: /\.(gif|jpg|jpeg|png|svg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 1024,
              name: 'resources/[path][name].[ext]'
            }
          }
        ]
      }
    ]
  }
}

module.exports = config

webpack.config.client.js

const path = require('path')
const merge = require('webpack-merge')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const baseConfig = require('./webpack.config.base')

const isDev = process.env.NODE_ENV === 'development'

const devServer = {
  port: 8010,
  host: '0.0.0.0', // 可以通过loaclhost、127.0.0.1、本机内网ip、手机等访问
  overlay: { // 将编译的错误显示到页面上
    errors: true
  },
  hot: true // 热加载
}

const defaultPlugin = [
  new VueLoaderPlugin(),
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: isDev ? '"development"' : '"production"'
    }
  }),
  new HtmlWebpackPlugin({
    template: path.join(__dirname, 'template.html')
  })
]

let config

if (isDev) {
  config = merge(baseConfig, {
    devtool: '#cheap-module-eval-source-map',
    module: {
      rules: [
        {
          test: /\.styl(us)?/,
          use: [
            'vue-style-loader',
            'css-loader',
            {
              loader: 'postcss-loader',
              options: {
                sourceMap: true
              }
            },
            'stylus-loader'
          ]
        }
      ]
    },
    devServer,
    plugins: defaultPlugin.concat([
      new MiniCssExtractPlugin({
        filename: '[name].[chunkHash:8].css',
        chunkFilename: '[name].[chunkHash:8].css'
      })
    ])
  })
} else {
  config = merge(baseConfig, {
    module: {
      rules: [
        {
          test: /\.styl(us)?/,
          use: [
            MiniCssExtractPlugin.loader,
            'css-loader',
            {
              loader: 'postcss-loader',
              options: {
                sourceMap: true
              }
            },
            'stylus-loader'
          ]
        }
      ]
    },
    plugins: defaultPlugin.concat([
      new MiniCssExtractPlugin({
        filename: '[name].[chunkHash:8].css',
        chunkFilename: '[name].[chunkHash:8].css'
      })
    ]),
    optimization: {
      splitChunks: {
        cacheGroups: { // 设置缓存组
          commons: {
            chunks: 'initial',
            minChunks: 2, // 在分割模块之前共享模块的最小块数(默认是1)
            maxInitialRequests: 5, // 入口点上的最大并行请求数(默认是3)
            minSize: 0
          },
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            chunks: 'initial',
            name: 'vendor',
            priority: 10,
            enforce: true
          }
        }
      },
      runtimeChunk: true
    }
  })
}

module.exports = config

最后安装两个有趣的工具pre-commit 和 rimraf

// pre-commit 预提交,简单的说就是提交到git的时候提前执行一遍
npm install --save-dev pre-commit 
// 用于删除dist目录
npm install --save-dev rimraf

在package.json中配置如下

  "scripts": {
    "precommit": "npm run lint-fix",
    "clean": "rimraf dist"
  },

pre-commit图:

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!