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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/achenyuan/article/details/83378923

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}`

猜你喜欢

转载自blog.csdn.net/achenyuan/article/details/83378923
今日推荐