1. 程式人生 > >webpack的DefinePlugin外掛實現多環境下配置切換

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