user18481
user18481

Reputation: 49

Webpack4 in production mode, does not uglify variable names in state of a React.Component?

The varialble names in state of a react component will not be changed in production mode by webpack 4.

I try "uglifyjs-webpack-plugin": "^2.1.3", but does not make a difference.

For instance,

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  // ...
}

I want in production, the state name count is been uglyfied. I expect something like,

this.state = {c:props.initialCount};

webpack.config.js is as follows, // load packages

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

// define the path

const STATIC_DIR = path.resolve(__dirname,
    'static',
    'app', 'js');
const SOURCE_DIR = path.resolve(STATIC_DIR, 'src');
module.exports = {
    mode: "production",
    devtool: 'source-map',

// define entry

    entry: {
        plugin: path.resolve(SOURCE_DIR, 'index.js')
    },

// define output

    output: {
        filename: '[name]-2.4.0.js',
        path: STATIC_DIR
    },

Here is the important part,

    module: {
        rules: [
            {
                test: /\.jsx?/,
                include: SOURCE_DIR,
                use: {
                    loader: 'babel-loader',
                    options: {
                        // compact: false,
                        // presets: ["es2015", "react"],
                        plugins: ['transform-class-properties']
                    }
                }
            }
        ]
    },
    externals: {
        jquery: 'jQuery'
    }
};

Upvotes: 1

Views: 479

Answers (2)

AKX
AKX

Reputation: 168967

Unfortunately I don't believe that's going to happen. The uglifier can't know how this.state is used and. For instance, you could index into it in a dynamic manner:

this.state = {count: 8};
console.log(this.state['c' + 'ount']);  // 8

Even if it could understand that that's not going to happen within the component, you could do

somethingElse(this.state);

and whatever somethingElse() is, it probably couldn't make heads or tails of this.state if its keys were minified.

I don't recommend it, but one way to achieve this in a roundabout way is to use string variables for keys and computed property names

const COUNT_KEY = (process.env.NODE_ENV === "production" ? 'c' : 'count');
this.state = {[COUNT_KEY]: 8};
console.log(this.state[COUNT_KEY]);

which might get uglified into e.g. this in production:

const t = "c";
this.state = {[t]: 8};
console.log(this.state[t]);

Upvotes: 1

Vijay sadhu
Vijay sadhu

Reputation: 500

you can put condition like this

if (process.env.NODE_ENV === "production") {
    this.state = {c:props.initialCount};     //execute in production time
} else {
    this.state = {count: props.initialCount};
}

Upvotes: 1

Related Questions