How to use the DefinePlugin function from webpack

Find comprehensive JavaScript webpack.DefinePlugin code examples handpicked from public code repositorys.

webpack.DefinePlugin is a plugin in the Webpack build tool used to define global constants that can be accessed by the application code at runtime.

65
66
67
68
69
70
71
72
73
74
      loader: "null-loader"
    }
  ]
},
plugins: [
  new webpack.DefinePlugin({
    "process.env.NODE_ENV": JSON.stringify(
      options.IS_PRODUCTION ? "production" : "development"
    ),
    TARGET: JSON.stringify(options.TARGET),
fork icon74
star icon252
watch icon28

86
87
88
89
90
91
92
93
94
95

const mainConfig = merge({}, commonConfig, {
  entry: { main: path.resolve(__dirname, 'src/main-process/main') },
  target: 'electron-main',
  plugins: [
    new webpack.DefinePlugin(
      Object.assign({}, replacements, {
        __PROCESS_KIND__: JSON.stringify('main'),
      })
    ),
fork icon0
star icon118
watch icon23

+ 19 other calls in file

How does webpack.DefinePlugin work?

webpack.DefinePlugin is a plugin provided by the Webpack build tool used to define global constants that can be accessed by the application code at runtime. When webpack.DefinePlugin is used in a Webpack configuration, it takes as input an object containing key-value pairs of constant names and values. These constants can be defined as strings, numbers, or booleans, and are inserted directly into the compiled code at build time. The constants defined by DefinePlugin can be accessed by the application code using process.env or any other mechanism for accessing global variables. For example, if you define a constant called API_URL with a value of "https://example.com/api", you can access it in your application code using process.env.API_URL. By defining constants with DefinePlugin, you can easily configure your application to use different values in different environments, such as development, staging, and production. This can help to avoid hardcoding values and make your application more flexible and maintainable. webpack.DefinePlugin is commonly used in Webpack configurations to define constants for use in the application code. By providing a simple and flexible interface for defining global constants, DefinePlugin can be used to customize the behavior of your application and optimize your build process.

70
71
72
73
74
75
76
77
78
79
resolve: {
  extensions: [".ts", ".tsx", ".js", ".css"],
},
plugins: [
  new MiniCssExtractPlugin(),
  new DefinePlugin({
    __COMMIT_HASH__: JSON.stringify(commitHash),
    __API_HOST__: JSON.stringify(
      process.env.NODE_ENV === "production"
        ? process.env.STAGE
fork icon4
star icon40
watch icon3

76
77
78
79
80
81
82
83
84
const resolveAlias = (compiler.options.resolve.alias =
  compiler.options.resolve.alias || {});
resolveAlias['book-loader/pages$'] = require.resolve('./pages-api');

compiler.apply(
  new webpack.DefinePlugin({ BOOK_LOADER_DIR: JSON.stringify(__dirname) })
);

new PageUrlPlugin().apply(compiler);
fork icon0
star icon2
watch icon1

Ai Example

1
2
3
4
5
6
7
8
9
10
const webpack = require("webpack");

module.exports = {
  // ...other Webpack configuration...
  plugins: [
    new webpack.DefinePlugin({
      API_URL: JSON.stringify("https://example.com/api"),
    }),
  ],
};

In this example, we first import the webpack module. We then define a Webpack configuration object with an array of plugins that includes a new instance of webpack.DefinePlugin. We define a constant called API_URL with a value of 'https://example.com/api'. We use JSON.stringify to ensure that the value is properly encoded as a string. This constant will be inserted into the compiled code at build time. In the application code, we can access the API_URL constant using process.env.API_URL or any other mechanism for accessing global variables. For example, we might use it to configure an API client: javascript Copy code

127
128
129
130
131
132
133
134
135
136

  const env = {
    [this.options.name]: JSON.stringify(envInfo),
  }

  new DefinePlugin(env).apply(compiler)
})

if (this.options.persistent) {
  compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
fork icon1
star icon1
watch icon2

54
55
56
57
58
59
60
61
62
63
64
  new webpack.EnvironmentPlugin({ WEBPACK_SERVE: null }),
  // similarly for a non-environment value
  // https://webpack.js.org/plugins/define-plugin/
  // but because ESlint runs *before* the DefinePlugin we need to
  // add it as a global variable in .eslintrc.json config file
  new webpack.DefinePlugin({ COCKPIT_TARGET_URL: JSON.stringify(cockpitTarget) }),
].filter(Boolean);


if (eslint) {
  plugins.push(new ESLintPlugin({ extensions: ["js", "jsx"], failOnWarning: true, }));
fork icon10
star icon36
watch icon14

150
151
152
153
154
155
156
157
158
159
    nodeModules: process.env.NODE_ENV !== 'production'
      ? path.resolve(__dirname, '../node_modules')
      : false
  }),
  new webpack.NoEmitOnErrorsPlugin(),
  new webpack.DefinePlugin(getRendererEnvironmentDefinitions()),
  new VueLoaderPlugin()
],
output: {
  filename: '[name].js',
fork icon0
star icon4
watch icon2

+ 3 other calls in file

606
607
608
609
610
611
612
613
614
615
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// Experimental hot reloading for React .
// https://github.com/facebook/react/tree/main/packages/react-refresh
isEnvDevelopment &&
  shouldUseReactRefresh &&
fork icon3
star icon4
watch icon2

43
44
45
46
47
48
49
50
51
52
  clean: true,
  filename: '[name].[contenthash].js',
  assetModuleFilename: 'assets/[name][ext]',
},
plugins: [
  new webpack.DefinePlugin(envKeys),
  new HtmlWebpackPlugin({
    template: path.resolve(__dirname, 'src', 'index.html'),
  }),
  new MiniCssExtractPlugin({
fork icon0
star icon0
watch icon1

23
24
25
26
27
28
29
30
31
32
33
  }, {});


  return {
    plugins: [
      new Webpack.EnvironmentPlugin(Object.keys(envParsed).map(key => key)),
      new Webpack.DefinePlugin(envKeys)
    ]
  };
};

fork icon0
star icon0
watch icon0

96
97
98
99
100
101
102
103
104
105
    result.plugins.push(new LicensePlugin(licensePluginConfig));
} else {
    result.devtool = "source-map";
}

result.plugins.push(new webpack.DefinePlugin(result.definitions));

delete result.definitions;
delete result.licenseConfig;
delete result.unacceptableLicenses;
fork icon0
star icon0
watch icon2

21
22
23
24
25
26
27
28
29
30
      'http://opensource.org/licenses/MIT',
      'Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.',
    ].join('\n'),
    entryOnly: true,
  }),
  new Webpack.DefinePlugin({
    __VERSION__: JSON.stringify(pkg.version),
    __TARGET__: JSON.stringify(__TARGET__),
  }),
];
fork icon0
star icon0
watch icon312

+ 3 other calls in file

52
53
54
55
56
57
58
59
60
61
62
const compressionPluginGzip = new CompressionPlugin({
    include: /vendor.js$/,
    // filename: 'vendor.js.gzip',
});


const processEnvironmentPlugin = new webpack.DefinePlugin({
    'process.env.ENV_MODE': JSON.stringify(process.env.ENV_MODE),
    'process.env.SC_DISABLE_SPEEDY': JSON.stringify(true), /** HACK: styled components not rendering in production */
    ...environment,
});
fork icon0
star icon0
watch icon0

454
455
456
457
458
459
460
461
462
463
      target, // 环境参数
      htmlWebpackPluginOptions
    }
  }
}),
// new webpack.DefinePlugin({
//   "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV)
//   // "process.env.DEBUG": JSON.stringify(process.env.DEBUG),
//   // "process.env.DefinePluginFlag": true
// }),
fork icon0
star icon0
watch icon0

62
63
64
65
66
67
68
69
70
71
          return content;
        }
      }
    ]
  }),
  new webpack.DefinePlugin(env_vars)
],
optimization: {
  splitChunks: {
    minSize: 1000000,
fork icon0
star icon0
watch icon0

121
122
123
124
125
126
127
128
129
130
            'luxon',
        ]),
    ],
}));

config.plugins.push(new webpack.DefinePlugin({
    'process.env.TARGET_IS_PRODUCT': TARGET_IS_PRODUCT, // TODO We might want a better name for this
}));

config.output = {
fork icon0
star icon0
watch icon547

133
134
135
136
137
138
139
140
141
142
                new CopyWebpackPlugin({
                        patterns: [
                                { from: 'src', to: '.', globOptions: { ignore: ['**/test/**', '**/*.ts'] }, noErrorOnMissing: true }
                        ]
                }),
                new DefinePlugin({ WEBWORKER: JSON.stringify(true) })
        ]
};

return merge(defaultConfig, extConfig);
fork icon0
star icon0
watch icon1

82
83
84
85
86
87
88
89
90
91

plugins.push(new webpack.ProvidePlugin({
  Promise: ['@electron/internal/common/webpack-globals-provider', 'Promise']
}));

plugins.push(new webpack.DefinePlugin(defines));

if (wrapInitWithProfilingTimeout) {
  plugins.push(new WrapperPlugin({
    header: 'function ___electron_webpack_init__() {',
fork icon0
star icon0
watch icon0

109
110
111
112
113
114
115
116
117
118
plugins: [
  process.env.ANALYZE &&
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
    }),
  new webpack.DefinePlugin({ VERSION: JSON.stringify(VERSION) }),
  // Generate a service worker script that will precache, and keep up to date,
  // the HTML & assets that are part of the Webpack build.
  new SWPrecacheWebpackPlugin({
    // By default, a cache-busting query parameter is appended to requests
fork icon0
star icon0
watch icon0