webpack.DefinePlugin使用介绍

webpack.DefinePlugin用于定义全局变量,避免了运行时的计算,提高性能。当试图将非字符串值转换为字符串时,可以使用JSON.stringify。在实际应用中,常用于根据开发或生产环境设置不同配置,如API地址和调试功能的开关。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个插件是用来定义全局变量的

//webpack.config.js
var webpack = require('webpack');
var path = require('path');

module.exports = {
    entry: {
        index: "./js/index.js"
    },
    output: {
        path: "./dist/",
        filename: "js/[name].js",
        chunkFilename: "js/[name].js"
    },
    plugins: [
        new webpack.DefinePlugin({
            SOMETHINE: 'This is something we needed.'
        })
    ]
};

//index.js
console.log('SOMETHINE=',SOMETHINE);

编译完结果如下:
在这里插入图片描述
可以看到代码中 SOMETHINE 被直接替换为 This is something we needed. 但是我们的本意中 SOMETHINE 是一个字符串,而直接替换后却不是一个字符串。

如何换成字符串

SOMETHINE: '"This is something we needed."'
//or借助JSON.stringify
SOMETHINE: JSON.stringify('This is something we needed.')

借助JSON.stringify不仅可以处理字符串,还可以处理Object中的字符串和Array

//webpack.config.js

 plugins: [
    new webpack.DefinePlugin({
        OBJ: JSON.stringify({"key1": "this is value"}),
        OBJ2: {"key1": "this is value"},
        OBJ3: {"key1": "'this is value'"},
        ARRAY: JSON.stringify(["value1", "value2"]),
        ARRAY2: ["value1", "value2"],
        ARRAY3: ["'value1'", "'value2'"],
// Number 和 Boolean 两种变量类型
        NUMBER: 12,
        BOOL: true
    })
]

//index.js
console.log('OBJ=', OBJ);//  OBJ= { key1: 'this is value' }
console.log('OBJ2=', OBJ2);//报错  console.log('OBJ2=', Object({"key1":this is value}));
console.log('OBJ3=', OBJ3);// OBJ3= { key1: 'this is value' }
console.log('ARRAY=', ARRAY);// ARRAY= [ 'value1', 'value2' ]
console.log('ARRAY2=', ARRAY2);// ARRAY2= {"0":value1,"1":value2}  value1 is not defined
console.log('ARRAY3=', ARRAY3);// ARRAY3= { '0': 'value1', '1': 'value2' }
console.log(NUMBER,BOOL);// 12 true

实际应用

在实际使用中, DefinePlugin 最为常用的用途就是用来处理我们开发环境和生产环境的不同。
比如一些 debug 的功能在生产环境中需要关闭、开发环境中和生产环境中 api 地址的不同。

// webpack.dev.conf.js
var config = require('../config')
...
new webpack.DefinePlugin({
  'process.env': config.dev.env
})

// webpack.prod.conf.js
var config = require('../config')
...
new webpack.DefinePlugin({
  'process.env': config.build.env
})


// index.js
if ('development' === process.env.NODE_ENV) {
 // 开发环境下的逻辑
} else {
 // 生产环境下
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值