• 启用多个服务器的webpack配置


      在前端开发工作中会遇到一个前端开发者与多个后端开发者进行接口联调,按照默认webpack的配置无法同时启用多个前端服务,这样来回改动webpack配置来切换启动前端服务给工作带来很多不便,鉴于提高工作效率,可以对webpack进行一下配置来接解决上面这个问题。

      首先将config/index.js中dev的host设置为 ' ';

      代码如下:

     1 module.exports = {
     2   dev: {
     3     // Paths
     4     env: require('./dev.env'),
     5     autoOpenBrowser: true,
     6     assetsSubDirectory: 'static',
     7     assetsPublicPath: '/',
     8     proxyTable: {
     9     },
    10     host: '', 
    11     port: 8090, 
    12   },
    13 
    14   build: {
    15   },
    16   cssSourceMap: false
    17 
    18 }

      然后在package.json中添加需要启用的端口号;

      代码如下:

    {
      "name": "szrbelement",
      "version": "1.0.0",
      "description": "a backstage templates for picc",
      "author": "",
      "private": true,
      "scripts": {
        "dev": "webpack-dev-server --inline --progress --open --config build/webpack.dev.conf.js",
        "dev_163": "SET PORT=10163 && SET TARGET=http://58.1.1.163/ && npm run dev",
        "dev_151": "SET PORT=10151 && SET TARGET=http://58.1.1.151/ && npm run dev",
        "dev_169": "SET PORT=10151 && SET TARGET=http://58.1.1.169/ && npm run dev", 
        "start": "npm run dev",
        "build": "node build/build.js"
      },
    }

      最后在build/webpack.dev.config.js中引入os模块获取本地ip地址(方便项目移植到不同pc终端运行),替换代理目标;

      代码如下:

    
    

      'use strict'
      const utils = require('./utils')
      const webpack = require('webpack')
      const config = require('../config')
      const merge = require('webpack-merge')
      const path = require('path')
      const baseWebpackConfig = require('./webpack.base.conf')
      const CopyWebpackPlugin = require('copy-webpack-plugin')
      const HtmlWebpackPlugin = require('html-webpack-plugin')
      const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
      const portfinder = require('portfinder')

    //引入os模块
    const os = require('os')

      const HOST = process.env.HOST
      const PORT = process.env.PORT && Number(process.env.PORT)

    // 获取代理目标
    const TARGET = process.env.TARGET
    if(TARGET){
     config.dev.proxyTable['/项目上下文'].target=TARGET
    }
    // 获取网卡IP
    var interfaces = os.networkInterfaces();
    var localIPAddress = "";
    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                localIPAddress = alias.address;
                break;
            }
        }
        if (localIPAddress) break;
    }
    localIPAddress = localIPAddress || "127.0.0.1"
    
    
    const devWebpackConfig = merge(baseWebpackConfig, {
      module: {
        rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
      },
      // cheap-module-eval-source-map is faster for development
      devtool: config.dev.devtool,
    
      // these devServer options should be customized in /config/index.js
      devServer: {
        clientLogLevel: 'warning',
        historyApiFallback: {
          rewrites: [
            { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
          ],
        },
        hot: true,
        contentBase: false, // since we use CopyWebpackPlugin.
        compress: true,
        host: HOST || config.dev.host || localIPAddress,    //更改获取ip地址的优先级
        port: PORT || config.dev.port,    //
        open: config.dev.autoOpenBrowser,
        overlay: config.dev.errorOverlay
          ? { warnings: false, errors: true }
          : false,
        publicPath: config.dev.assetsPublicPath,
        proxy: config.dev.proxyTable,    
        quiet: true, // necessary for FriendlyErrorsPlugin
        watchOptions: {
          poll: config.dev.poll,
        }
      },
      plugins: [
        new webpack.DefinePlugin({
          'process.env': require('../config/dev.env')
        }),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
        new webpack.NoEmitOnErrorsPlugin(),
        // https://github.com/ampedandwired/html-webpack-plugin
        new HtmlWebpackPlugin({
          filename: 'index.html',
          template: 'index.html',
          inject: true
        }),
        // copy custom static assets
        new CopyWebpackPlugin([
          {
            from: path.resolve(__dirname, '../static'),
            to: config.dev.assetsSubDirectory,
            ignore: ['.*']
          }
        ])
      ]
    })

      接下来我们可以在vs code终端执行npm run dev_163来启动服务,还可以利用dos命令同时启动多个服务,在项目文件下新建startall.bat文件,文件内容如下:

    start /b npm run dev_163
    start /b npm run dev_151
    start /b npm run dev_169

      如有任何疑问或有指正的地方欢迎在下方留言,非常感谢!

  • 相关阅读:
    【hdu 4135】Co-prime
    【cdoj 1544】当咸鱼也要按照基本法
    【SRM 717 DIV2 C】DerangementsDiv2
    【codeforces 821E】Okabe and El Psy Kongroo
    【SRM 717 div2 B】LexmaxReplace
    【SRM 717 div2 A】 NiceTable
    Network architecture for minimalistic connected objects
    C# 委托的理解
    50条超精辟的经典语录:哗众,可以取宠,也可以失宠!
    50条超精辟的经典语录:哗众,可以取宠,也可以失宠!
  • 原文地址:https://www.cnblogs.com/yanganglanyu/p/10620363.html
Copyright © 2020-2023  润新知