08 webpack4.0学习笔记——配置文件_DefinePlugin使用

概述

        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插件的使用,此插件在我们实际项目开发中运用的比较多,所以大家要花精力再研究研究哦。

发布了112 篇原创文章 · 获赞 109 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/qq_35117024/article/details/91876326