babel / minify

:scissors: An ES6+ aware minifier based on the Babel toolchain (beta)
https://babeljs.io/repl
MIT License
4.39k stars 225 forks source link

babel-plugin-minify-dead-code-elimination only useful for entry scripts #879

Open kingback opened 6 years ago

kingback commented 6 years ago

Describe the bug

babel-plugin-minify-dead-code-elimination only useful for entry scripts, the dependencies is not working.

To Reproduce

index.js

import { setTitle } from './utils';
const isWeb = true;

setTitle('test');

if (isWeb) {
  console.log(isWeb);
} else {
  console.log(!isWeb);
}

utils.js

const isWeb = true;

export function setTitle(title) {
  if (isWeb) {
    document.title = title;
  } else {
    console.log(title);
  }
}

Actual Output

index.js, correct

import { setTitle } from './utils';
const isWeb = true;
setTitle('test');
console.log(isWeb);

utils.js, uncorrect

const isWeb = true;

export function setTitle(title) {
  if (isWeb) {
    document.title = title;
  } else {
    console.log(title);
  }
}

Expected Output

utils.js

const isWeb = true;
export function setTitle(title) {
  document.title = title;
}

Configuration

How are you using babel-minify?

webpack.config.js

const path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/index/index.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'bundle.js'
  },
  optimization: {
    minimize: false
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        options: {
          presets: ['env'],
          plugins: ['minify-dead-code-elimination']
        }
      }
    ]
  }
};

package.json

{
  "name": "test-dce",
  "version": "1.0.0",
  "description": "test dead code elimination",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --mode development",
    "build": "webpack --mode production"
  },
  "repository": {},
  "keywords": [],
  "author": "huya.nzb@alibaba-inc.com",
  "license": "MIT",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-minify-dead-code-elimination": "^0.4.3",
    "babel-preset-env": "^1.7.0",
    "webpack": "^4.14.0",
    "webpack-cli": "^3.0.8",
    "webpack-dev-server": "^3.1.4"
  },
  "dependencies": {}
}
kingback commented 6 years ago

babel-plugin-minify-dead-code-elimination: "^0.3.0" is OK

boopathi commented 6 years ago

Repro:

const isWeb = true;

export function setTitle(title) {
  if (isWeb) {
    document.title = title;
  } else {
    console.log(title);
  }
}

is not minified. I think some bailing out caused this.