webpack的DefinePlugin插件实现多环境下配置切换

webpack的DefinePlugin插件实现多环境下配置切换

前言

在使用springboot开发后台时,可以使用spring.profies.active实现应用程序在不同的环境可能会有不同的配置,例如数据库连接、日志级别等,开发,测试,生产每个环境可能配置都不一致。
其实webpack模块化开发也能实现。
DefinePlugin 允许创建一个在编译时可以配置的全局常量。这可能会对开发模式和发布模式的构建允许不同的行为非常有用。如果在开发构建中,而不在发布构建中执行日志记录,则可以使用全局常量来决定是否记录日志。这就是 DefinePlugin 的用处,设置它,就可以忘记开发和发布构建的规则。

语法

new webpack.DefinePlugin({
  // Definitions...
})

其实很简单,就配置一下即可

实例

例如,开发环境的配置文件webpack.dev.config

new webpack.DefinePlugin({
        "test":"666",
        test1:"777",
        test2:{name:"123",age:12},
        "typeof test3":JSON.stringify("object"),
         test4: JSON.stringify(false)
    })

在项目里定义一个config.js,使用方式如下

console.log(test)
console.log(test1)
console.log(test2)
console.log(typeof test3)
console.log(test4)

可以直接拿到值,结果如下

在这里插入图片描述

其中,我们常用的是test1,test2,test4的方式

项目实战

开发环境,webpack.dev.config:

webpackConfig.plugins = [
    ...webpackConfig.plugins,
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
        DEVELEPMENT: JSON.stringify(true),
        PRODUCTION: JSON.stringify(false),
    })
];
webpackConfig.mode = 'development'
module.exports = webpackConfig;

生产环境,webpack.prod.config.js

webpackConfig.plugins = [
    ...webpackConfig.plugins,
    new webpack.DefinePlugin({
        DEVELEPMENT: JSON.stringify(false),
        PRODUCTION: JSON.stringify(true),
    })
];
webpack.mode = 'production'
module.exports = webpackConfig;

使用文件config.js:

if(PRODUCTION){
    console.log(window.location)
    let wsProtocol = "wss://"
    if(window.location.protocol === "http:"){
        wsProtocol = "ws://"
    }
    var sockServer = `${wsProtocol}${window.location.host}`
}else if(DEVELEPMENT){
    var sockServer = `ws://127.0.0.1:9999`
}

export default{
    sockServer
}

config.js通过没有使用压缩的 webpack 的结果:

if(false){
    console.log(window.location)
    let wsProtocol = "wss://"
    if(window.location.protocol === "http:"){
        wsProtocol = "ws://"
    }
    var sockServer = `${wsProtocol}${window.location.host}`
}else if(true){
    var sockServer = `ws://127.0.0.1:9999`
}

export default{
    sockServer
}

通过使用压缩的 webpack 的结果:

	console.log(window.location)
    let wsProtocol = "wss://"
    if(window.location.protocol === "http:"){
        wsProtocol = "ws://"
    }
    var sockServer = `${wsProtocol}${window.location.host}`
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值