Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include and use DefinePlugin in webpack config?

Hi there i am trying to use the define plugin so i can update the version number to make sure my JS refreshes after releasing a new build. I can't seem to get DefinePlugin to work properly though. I see it in the folder webpack and i'm trying to follow the documentation but i get errors that it isn't found. Here is my config:

const path = require('path'),
settings = require('./settings');

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpack = require('webpack');


module.exports = {
  entry: {
    'scrollerbundled': [settings.themeLocation + "js/scroller.js"],
    'mapbundled': [settings.themeLocation + "js/shopmap.js"],
    'sculptor': [settings.themeLocation + "js/sculptor.js"]
  },
  output: {
    path: path.resolve(__dirname, settings.themeLocation + "js-dist"),
    filename: "[name].js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ],
    plugins: [new webpack.DefinePlugin({
    PRODUCTION: JSON.stringify(true),
    VERSION: JSON.stringify('5fa3b9'),
  })]
  },
  optimization: {
    minimizer: [new UglifyJsPlugin({ 
            uglifyOptions: {
                mangle: true,
                output: {
                    comments: false
                }
            }
       })]
  },
  mode: 'production'
}
like image 208
Tintinabulator Zea Avatar asked Jan 18 '19 23:01

Tintinabulator Zea


People also ask

What is DefinePlugin in webpack?

The DefinePlugin replaces variables in your code with other values or expressions at compile time. This can be useful for allowing different behavior between development builds and production builds.


1 Answers

I Have "webpack": "^4.28.4" and define in webpack config

new webpack.DefinePlugin({
 PRODUCTION: JSON.stringify(true),
});

if you console that variables, you don't find it. I use in conditional

if (PRODUCTION) {
 //do stuff
}

Another case is to set globals variables in a object and share with webpack.

here is an example

        new webpack.ProvidePlugin({
        CONFIG: path.resolve(__dirname, './CONSTS.js')
        }),
        // the path is src/CONST.JS

In the eslintrc file you can add that variables to avoid import errors.

    "settings": {
     "import/resolver": {
      "webpack": {
       "config": "webpack.dev.js"
      }
     }
    }

then in any file you can use import {value} from 'CONFIG'

like image 53
Fernando Colom Avatar answered Sep 28 '22 08:09

Fernando Colom