fix(html): support import.meta.env define replacement without quotes#13425
fix(html): support import.meta.env define replacement without quotes#13425bluwy merged 6 commits intovitejs:mainfrom
import.meta.env define replacement without quotes#13425Conversation
|
|
| if (typeof val === 'string') { | ||
| try { | ||
| env[key.slice(16)] = JSON.parse(val) | ||
| } catch {} // ignore non-JSON.parse-able values | ||
| } else { | ||
| env[key.slice(16)] = JSON.stringify(val) | ||
| } |
There was a problem hiding this comment.
Or maybe we should just support JSON.stringified strings?
| if (typeof val === 'string') { | |
| try { | |
| env[key.slice(16)] = JSON.parse(val) | |
| } catch {} // ignore non-JSON.parse-able values | |
| } else { | |
| env[key.slice(16)] = JSON.stringify(val) | |
| } | |
| if (typeof val === 'string') { | |
| try { | |
| env[key.slice(16)] = JSON.parse(val) | |
| } catch {} // ignore non-JSON.parse-able values | |
| } |
There was a problem hiding this comment.
Yes, I think it is better we only support stringified object/strings. It isn't intuitive from a HTML-only perspective, but IMO it is better to be consistent between JS and HTML here.
I wonder if we really need to support define for HTML though, or we could remove this 958-964 and add a note in the docs if this is confusing for users 🤔
In JS, it makes sense because we replace the whole import.meta.env.VITE_STRING
define: {
'import.meta.env.VITE_STRING': JSON.stringify('string'),
},
But in HTML we have %VITE_STRING%. Supporting define in HTML feels like formalizing that define for import.meta.env.VITE_XXX is not a replacement that happens before the regular env replacement, but a way to overwrite env variables in the config. If we would like this feature, maybe we should have a new envOverrides config option?
There was a problem hiding this comment.
I use the define for HTML to have a document title from the first page load and reuse the same variable through my js code.
If we don't support it, I would have to hard code the value in HTML and add the same value in a js constant.
There was a problem hiding this comment.
Non JSON.stringified strings break the code already here.
So I think it is fair to discard not stringified strings with a warning log maybe?
There was a problem hiding this comment.
I think this shows that supporting define in HTML isn't being used as intended though. We wanted to only add support for replacing env variables. And you are going through a define to override a non-existent env variable to be able to use this feature. I think it is better for you to use an inline plugin and transformIndexHtml.
There was a problem hiding this comment.
I think we did for JS, it feels a bit of a stretch to me to also support it in HTML. But IIRC, there was a discussion about allowing env to be a config object to have these kind of features (env.declare or env.define maybe)? Maybe
define: {
'import.meta.env.VITE_STRING': JSON.stringify('string'),
},looks intuitive to others. I'm fine if both you and @sapphi-red would like to move on with this PR, as we'll still need to do the breaking change to remove support for this.
There was a problem hiding this comment.
I think overloading define to extend import.meta.env.* is fine since it's not a common thing to do, but happy to discuss more about it if it's confusing. The HTML case is indeed a bit tricky but I think a fix like this could be good enough for now.
EDIT: I didn't notice the PR is marked as a breaking change. I'm slightly leaning towards maybe not, depending on how safe we want to play it 😄
There was a problem hiding this comment.
I'm leaning towards applying this suggestion (#13425 (comment)).
We document the behavior as "Any properties in import.meta.env can be used in HTML files with a special %ENV_NAME% syntax". I understood it to mean replacing %ENV_NAME% with the value of the element in import.meta.env. So it's the value when executed by JS and not the value written in the source code. From that standpoint, we might say that this is not a breaking change.
I think overloading
defineto extendimport.meta.env.*is fine since it's not a common thing to do, but happy to discuss more about it if it's confusing.
To be honest, a few month ago I didn't know that it works like that. I thought it's a simple replacement but if import.meta.env.* is defined it affects import.meta.env too. (#12866 (comment), #13003)
I think it's confusing that it does more than a simple replacement but I guess it's fine to have this behavior if we add a document about this behavior.
There was a problem hiding this comment.
I'm leaning towards applying this suggestion (#13425 (comment)).
What happens for import.meta.env.* that are numbers or booleans though. I think it makes sense to replace e.g. <p>%LEGACY%</p> to <p>false</p>
There was a problem hiding this comment.
I was wondering whether it's confusing to allow that. But yeah, it would be better to have access to number/boolean import.meta.envs.
|
I pushed some commits to support values with single/back quotes and to add a warning for ignored ones. |
| if (typeof val === 'string') { | ||
| try { | ||
| env[key.slice(16)] = extractStringLiteral(val) | ||
| } catch { | ||
| ignoredImportMetaEnvKeys.add(key.slice(16)) | ||
| } |
There was a problem hiding this comment.
IIUC extractStringLiteral would prevent usages like:
define: {
'import.meta.env.NULL_STR': 'null'
}(It's a bit of a stretch though 😅)
I wonder if doing:
| if (typeof val === 'string') { | |
| try { | |
| env[key.slice(16)] = extractStringLiteral(val) | |
| } catch { | |
| ignoredImportMetaEnvKeys.add(key.slice(16)) | |
| } | |
| if (typeof val === 'string') { | |
| try { | |
| env[key.slice(16)] = JSON.parse(val) | |
| } catch { | |
| env[key.slice(16)] = val | |
| } |
Would be good enough to prevent the breaking change. I've also made a stackblitz to test things out. Looking back it seems to be a hard feature to balance, and I could be persuaded that the original issue (#13424) could be working as intended too.
There was a problem hiding this comment.
Yeah... It's hard.
I removed the warning and made it do the fallback instead. I think it would be intuitive to support single/back quotes so I left the support for them.
There was a problem hiding this comment.
I stil don't quite understand why we have special treatment using extractStringLiteral. Couldn't we use JSON.parse here?
There was a problem hiding this comment.
define: {
'import.meta.env.DOUBLE_QUOTE': "'foo'",
'import.meta.env.SINGLE_QUOTE': "'foo'",
'import.meta.env.BACK_QUOTE': "`foo`"
}If we use JSON.parse, import.meta.env.SINGLE_QUOTE will be replaced with 'foo'. But I think people will expect that to be replaced with foo like import.meta.env.DOUBLE_QUOTE works.
extractStringLiteral + fallback |
JSON.parse + fallback |
|
|---|---|---|
| DOUBLE_QUOTE | foo |
foo |
| SINGLE_QUOTE | foo |
'foo' |
| BACK_QUOTE | foo |
`foo` |
There was a problem hiding this comment.
I think that's fine for now to reduce complexity, they can workaround it by using "\"foo\"" (which is usually what JSON.stringify generates) 🤔 I'm mostly concern of the additional code here that's needed to maintain for a (seemingly) simple feature.
import.meta.env define replacement without quotes
|
Code Review AI:
function extractStringLiteral(source: string): string {
try {
// existing code
} catch (error) {
console.warn(`Failed to extract string literal from source: ${source}`);
return source;
}
}
const IMPORT_META_ENV_LENGTH = `import.meta.env.`.length;
// later in the code
env[key.slice(IMPORT_META_ENV_LENGTH)] = JSON.stringify(val); |
|
@oarsheo please avoid sending AI-generated code reviews to the Vite repo. Thanks! |
| const parsed = JSON.parse(val) | ||
| env[key.slice(16)] = typeof parsed === 'string' ? parsed : val |
There was a problem hiding this comment.
I totally forgot about this PR 😅
I replaced extractStringLiteral with this one.
The typeof parsed === 'string' thing is to avoid a breaking change when define has something like 'import.meta.env.VITE_OBJECT_STRING': '{ "foo": "bar" }'.
bluwy
left a comment
There was a problem hiding this comment.
Thanks for making the change! I think we can mark this as a fix() too?
import.meta.env define replacement without quotesimport.meta.env define replacement without quotes
|
I'm fine with moving forward with this fix, even if I still have doubts about the way we are extending |
Description
I'm not sure if this is the best way to solve this.
fixes #13424
refs #12202
Additional context
What is the purpose of this pull request?
Before submitting the PR, please make sure you do the following
fixes #123).