概述
DefinePlugin用來做定義。這就類似於我們項目開發中的config文件一樣,在config文件中一般放的是系統代碼中的一些服務器地址之類的公共信息,我們將這些信息提取出來單獨放在配置文件中,方便於後期的維護和管理。
那DefinePlugin的功能和config這個文件類似,我們可以在它裏面定義一些公有信息,然後在代碼裏直接使用,接下來我們來看詳細操作步驟。
具體操作步驟
1、根據官網的介紹我們來配置此插件,如下:
2、然後在我們的input.js文件中來使用這個變量SERVER_URL,如下:
上述代碼可看到,我們在代碼裏並沒有事先引入其他信息,直接使用SERVER_URL這個變量的。
3、到這一步,如果我們進行打包處理的話會出現報錯信息,因爲我們的defineplugin插件是webpack所屬之下的,所以我們要在配置文件的頂部還要引入webpack,如下:
4、這樣一來,我們再次執行打包處理後,就會生成結果文件,打開結果文件搜索fetch關鍵字可看到,在此處它請求的不再是我們定義的變量,而是一個具體的url地址,如下:
5、本文的配置文件代碼和input.js入口文件代碼,完整版如下:
配置文件:
const path=require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpack=require('webpack');
module.exports={
entry:'./input.js',
output:{
path:path.resolve(__dirname,'dist'),
filename:'output.bundle.js'
},
mode:'development',
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
new webpack.DefinePlugin({
'SERVICE_URL': JSON.stringify('https://dev.example.com')
}),
],
module:{
rules:[
{
test:/\.(png|jpg|gif)$/i,
use:[
{
loader:'url-loader',
options:{
limit:919200
}
}
]
},
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-react-jsx']
}
}
},
{
test: /\.scss$/,
use: [
// fallback to style-loader in development
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
]
}
};
入口文件:
const good='hello';
import HelloReact from './HelloReact.jsx';
import './test.scss';
import img1 from './img/01.png';
import img2 from './img/02.jpg';
//ES6中的語法 異步處理
async function sayHello(){
const result=await fetch(SERVICE_URL);
console.log(result);
}
sayHello();
總結
本文介紹了defineplugin插件的使用,此插件在我們實際項目開發中運用的比較多,所以大家要花精力再研究研究哦。