Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define doesn't apply to optionally chained variables #2324

Closed
hansottowirtz opened this issue Jun 16, 2022 · 4 comments
Closed

Define doesn't apply to optionally chained variables #2324

hansottowirtz opened this issue Jun 16, 2022 · 4 comments

Comments

@hansottowirtz
Copy link

I would like to replace a?.b with a variable, but it's not possible yet to use define for this. I think it would be valid in every case to add this functionality.

Example:

echo 'console.log(a.b)' | npx esbuild --define:'a.b'="'x'" # console.log("x")
echo 'console.log(a?.b)' | npx esbuild --define:'a.b'="'x'" # console.log(a.b)

Would it be possible to implement this as well, or is there some kind of workaround available?

@hyrious
Copy link

hyrious commented Jun 17, 2022

echo 'console.log(a?.b)' | esbuild --define:a='{"b":"x"}'
var define_a_default = { b: "x" };
console.log(define_a_default?.b);

@evanw
Copy link
Owner

evanw commented Jun 17, 2022

I don't have time to check right now, but I'd want to check how this feature behaves in other bundlers before implementing this (e.g. Webpack). Ideally esbuild would behave the same way.

@hansottowirtz
Copy link
Author

echo 'console.log(a?.b)' | esbuild --define:a='{"b":"x"}'

This would work, but in my case the a object is large, and this approach means it can't be tree-shaken.

@hansottowirtz
Copy link
Author

@evanw This behavior works in Webpack using DefinePlugin:

// webpack.config.js
const webpack = require('webpack');

/** @type {import('webpack').Configuration} */
const config = {
  mode: 'production',
  entry: './index.js',
  output: {
    filename: './out.js'
  },
  plugins: [
    new webpack.DefinePlugin({
      'a.b': '"x"'
    })
  ]
}

module.exports = config;
// index.js
console.log(a.b);
console.log(a?.b);
// out.js
console.log("x"),console.log("x");

@hansottowirtz hansottowirtz changed the title Define doesn't apply optionally chained variables Define doesn't apply to optionally chained variables Jun 17, 2022
@evanw evanw closed this as completed in bb97fc2 Jun 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants