日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

webpack.DefinePlugin使用介绍

發布時間:2025/3/21 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 webpack.DefinePlugin使用介绍 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這個插件是用來定義全局變量的

//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.jsplugins: [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 {// 生產環境下 } 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀

總結

以上是生活随笔為你收集整理的webpack.DefinePlugin使用介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。