Add ability to define custom variables #194
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Add
--define
flag for defining custom variables that will be replaced at build-time. It usesbabel-plugin-transform-replace-expressions
under the hood. to replace expressions with values in noth your source code (insrc
) and in yournode_modules
as well. Other babel transforms are NOT executed onnode_modules
at this time, just this special replace-expression plugin.Usage
Pass a comma-separated list of key-values to the
--define
flag in yourpackage.json
. You do not need to add quotes for strings values. Numbers WILL be cast to numbers automagically.Example
We want to define
ZOOP
as "foo" andVERSION
as2
to in our package.First, to get TypeScript to play nicely, you should add a
./src/env.d.ts
file with variable declarations.Now we can use these like they were magically equivalent to whatever we set them to. Since these are treated as values by TypeScript, you do not need to import them.
In our package.json, we use the
--define
flagWhen we run
yarn build
oryarn start
, TSDX will do the replacements and our output will look like this... (note: only including CJS outputs for brevity, replacements are made in all module formats).Future Work / Discussion