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

[Bug]: The code cannot be minimized. There are two references #1048

Open peacejj opened 9 months ago

peacejj commented 9 months ago

💻

How are you using Babel?

babel-loader (webpack)

Input code

Below is an example.


var babel = require('@babel/core');

var code = `
function baz() {
    const pageSource = 'pageSource';
    const clientType = 0;
    const isNavBack = true;
    const route = \`/pages/a/index?pageSource=\${pageSource}&clientType=\${clientType}&isNavBack=\${isNavBack}\`;

    React.api.navigateTo({
        url: route
    });
}
`

const result = babel.transform(code, {
    configFile: false,
    babelrc: false,
    comments: false,
    ast: true,
    sourceMaps: false,
    plugins: [
        [ require('@babel/plugin-transform-template-literals'), { loose: true }],
        ["minify-dead-code-elimination"],

    ]
});
console.log(result.code);

Be careful, To comment out node_modules/babel-plugin-minify-dead-code-elimination/lib/index.js (traverse.clearCache ||) traverse.cache.clear)();

Current and expected behavior

The current performance is:

function baz() {
  const pageSource = 'pageSource';
  const clientType = 0;
  const isNavBack = true;
  React.api.navigateTo({
    url: "/pages/a/index?pageSource=" + pageSource + "&clientType=" + clientType + "&isNavBack=" + isNavBack
  });
}

And here's what I was hoping for:

function baz() {
  React.api.navigateTo({
    url: "/pages/a/index?pageSource=" + "pageSource" + "&clientType=" + 0 + "&isNavBack=" + true
  });
}

After checking, it is found that @babel/plugin-transform-template-literals causes the number of references to be 2 when minify-dead-code-elimination plug-in is running, so it cannot be minimized. Is there any way to solve this problem

Environment

babel/core: 7.22.9

Possible solution

No response

Additional context

No response

babel-bot commented 9 months ago

Hey @peacejj! We really appreciate you taking the time to report an issue. The collaborators on this project attempt to help as many people as possible, but we're a limited number of volunteers, so it's possible this won't be addressed swiftly.

If you need any help, or just have general Babel or JavaScript questions, we have a vibrant Slack community that typically always has someone willing to help. You can sign-up here for an invite.

liuxingbaoyu commented 9 months ago

babel-plugin-minify-dead-code-elimination is no longer maintained. It is recommended that you use other tools such as terser.