Home > Web Front-end > JS Tutorial > How to Define Global Variables in Your Webpack Configuration?

How to Define Global Variables in Your Webpack Configuration?

Patricia Arquette
Release: 2024-11-09 07:38:02
Original
429 people have browsed it

How to Define Global Variables in Your Webpack Configuration?

Defining Global Variables with Webpack

In your webpack configuration, you can use various methods to define global variables.

1. Modules

Create a module and export an object containing your global variables. Import this module and access the variables.

// config.js
export default {
  FOO: 'bar',
};

// somefile.js
import CONFIG from './config.js';
console.log(`FOO: ${CONFIG.FOO}`);
Copy after login

2. ProvidePlugin

Use the ProvidePlugin to make a module available as a global variable. This plugin only includes the module in those modules where you use it.

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

module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      utils: 'utils',
    }),
  ],
};
Copy after login

3. DefinePlugin

Use the DefinePlugin to define global constants as JSON strings.

// webpack.config.js
const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      PRODUCTION: JSON.stringify(true),
      VERSION: JSON.stringify('5fa3b9'),
    }),
  ],
};
Copy after login

4. Global Object

Access the global object (window in browsers, global in Node) to define global variables.

// SPA or browser environment
window.foo = 'bar';

// Webpack will convert global to window
global.foo = 'bar';
Copy after login

5. Dotenv (Server Side)

Use the dotenv package to load environment variables from a .env file into Node's process.env.

// server.js
require('dotenv').config();

const db = require('db');
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS,
});
Copy after login

The above is the detailed content of How to Define Global Variables in Your Webpack Configuration?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template