代码阅读-》公司使用的 webpack 构建过程中修改模块请求解析方式

195 阅读1分钟

问题概述

在我们的项目中,遇到一个问题:代码中某些模块的路径在文件系统中不存在,但构建后的应用仍然可以正常运行。以下是相关代码段和配置的详细分析。

代码

router/index.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './router_VUE_APP_APP_PLUGIN.config'  // 注意:此路径在文件系统中不存在

Vue.use(VueRouter)

// 解决路由重复点击报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const loadRouters = routes

const router = new VueRouter({
  mode: 'history',
  base: Vue.GLOBAL_ENV.VUE_APP_PUBLIC_PATH,
  routes: loadRouters
})

export default router

图示路径问题:

img_2024_06_05_14_12_29.png

解决方案配置

vue.config.js:

const webpack = require('webpack')
const globalEnv = require('./globalEnv')

module.exports = {
  chainWebpack: config => {
    config.plugin('normal-module-replacement').use(webpack.NormalModuleReplacementPlugin, [
      /.*VUE_APP_APP_PLUGIN\./,
      function (resource) {
        resource.request = resource.request.replace(/VUE_APP_APP_PLUGIN/, globalEnv.VUE_APP_APP_PLUGIN)
      }
    ])
  }
}

globalEnv.js:

const GLOBAL_ENV = Object.create(null)

Object.assign(GLOBAL_ENV, {
  VUE_APP_APP_PLUGIN: 'SINGLE_APP'
})

module.exports = GLOBAL_ENV

学习点:NormalModuleReplacementPlugin 的使用

功能和应用场景

NormalModuleReplacementPlugin 是一个 webpack 插件,用于在编译过程中替换特定的模块请求。主要应用场景包括:

  • 动态模块路径配置:根据不同的部署环境(开发、测试、生产)动态更改模块路径。
  • 模拟和集成测试:在测试环境中替换某些模块,以便进行更加灵活的模拟和测试。

总结

通过使用 NormalModuleReplacementPlugin,我们可以根据环境变量动态修改模块请求路径。在本例中,根据 globalEnv.VUE_APP_APP_PLUGIN 的值,./router_VUE_APP_APP_PLUGIN.config 被替换为有效的路径 ./router_SINGLE_APP.config。这种方法提高了应用的配置灵活性和可维护性,特别是在多环境部署中非常有用。