Title: Proposal: Conditional Compilation · Issue #3538 · microsoft/TypeScript · GitHub
Open Graph Title: Proposal: Conditional Compilation · Issue #3538 · microsoft/TypeScript
X Title: Proposal: Conditional Compilation · Issue #3538 · microsoft/TypeScript
Description: Proposal: Conditional Compilation Problem Statement At design time, developers often find that they need to deal with certain scenarios to make their code ubiquitous and runs in every environment and under every runtime condition. At bui...
Open Graph Description: Proposal: Conditional Compilation Problem Statement At design time, developers often find that they need to deal with certain scenarios to make their code ubiquitous and runs in every environment a...
X Description: Proposal: Conditional Compilation Problem Statement At design time, developers often find that they need to deal with certain scenarios to make their code ubiquitous and runs in every environment a...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/3538
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Proposal: Conditional Compilation","articleBody":"# Proposal: Conditional Compilation\n## Problem Statement\n\nAt design time, developers often find that they need to deal with certain scenarios to make their code ubiquitous and runs in every environment and under every runtime condition. At build time however, they want to emit code that is more suited for the runtime environment that they are targetting by not emitting code that is relevant to that environment.\n\nThis is directly related to #449 but it also covers some other issues in a similar problem space.\n## Similar Functionality\n\nThere are several other examples of apporaches to solving this problem:\n- In C#, this is solved via [conditional flags](https://msdn.microsoft.com/en-us/library/aa691099%28v=vs.71%29.aspx) as well well as [conditional symbols](https://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute%28v=vs.90%29.aspx).\n- In Dojo, this was solved via adopting [has.js](https://github.com/phiggins42/has.js/) and static flags in the build tool that would allow build time \"dead code removal\".\n- IE used to support [conditional compilation](https://msdn.microsoft.com/library/121hztk3%28v=vs.94%29.aspx) using comments.\n- UglifyJS accomplishes this via [assertion of constants](https://github.com/mishoo/UglifyJS2#conditional-compilation) coupled with dead code removal.\n## Considerations\n\nMost of the solutions above use \"magic\" language features that significantly affect the AST of the code. One of the benefits of the _has.js_ approach is that the code is transparent for runtime feature detection and build time optimisation. For example, the following would be how design time would work:\n\n``` js\nhas.add('host-node', (typeof process == \"object\" && process.versions && process.versions.node && process.versions.v8));\n\nif (has('host-node')) {\n /* do something node */\n}\nelse {\n /* do something non-node */\n}\n```\n\nIf you then wanted to do a build that targeted NodeJS, then you would simply assert to the build tool (`staticHasFlags`) that instead of detecting that feature at runtime, `host-node` was in fact `true`. The build tool would then realise that the `else` branch was unreachable and remove that branch from the built code.\n\nBecause the solution sits entirely within the language syntax without any sort of \"magical\" directives or syntax, it does not take a lot of knowledge for a developer to leverage it.\n\nAlso by doing this, you do not have to do heavy changes to the AST as part of the complication process and it should be easy to identify branches that are \"dead\" and can be dropped out of the emit.\n\nOf course this approach doesn't specifically address conditionality of other language features, like the ability to conditionally load modules or conditional classes, though there are other features being introduced in TypeScript (e.g. local types #3266) which when coupled with this would address conditionality of other language features.\n## Proposed Changes\n\nIn order to support conditional compile time emitting, there needs to be a language mechanic to identify blocks of code that should be emitted under certain conditions and a mechanism for determining if they are to be emitted. There also needs to be a mechanism to determine these conditions at compile time.\n### Defining a Conditional Identifier at Design Time\n\nIt is proposed that a new keyword is introduced to allow the introduction of a different class of identifier that is neither a variable or a constant. Introduction of a TypeScript only keyword should not be taken lightly and it is proposed that either `condition` or `has` is used to express these identifiers. When expressed at design time, the identifier will be given a value which can be evaluated at runtime, with block scope. This then can be substituted though a compile time with another value.\n\nOf the two keywords, this proposal suggests that `has` is more functional in meaning, but might be less desirable because of potential for existing code breakage, but examples utlise the `has` keyword.\n\nFor example, in TypeScript the following would be a way of declaring a condition:\n\n``` typescript\nhas hostNode: boolean = Boolean(typeof process == \"object\" && process.versions && process.versions.node && process.versions.v8);\n\nif (hostNode) {\n console.log('You are running under node.');\n}\nelse {\n console.log('You are not running under node.');\n}\n```\n\nThis would then emit, assuming there is no compile time substitutional value available (and targeting ES6) as:\n\n``` javascript\nconst hostNode = Boolean(typeof process == \"object\" && process.versions && process.versions.node && process.versions.v8);\nif (hostNode) {\n console.log('You are running under node.');\n}\nelse {\n console.log('You are not running under node.');\n}\n```\n### Defining the value of a Conditional Identifier at Compile Time\n\nIn order to provide the compile time values, an augmentation of the `tsconfig.json` is proposed. A new attribute will be proposed that will be named in line with the keyword of either `conditionValues` or `hasValues`. Different `tsconfig.json` can be used for the different builds desired. Not considered in this proposal is consideration of how these values might be passed to `tsc` directly.\n\nHere is an example of `tsconfig.json`:\n\n``` json\n{\n \"version\": \"1.6.0\",\n \"compilerOptions\": {\n \"target\": \"es5\",\n \"module\": \"umd\",\n \"declaration\": false,\n \"noImplicitAny\": true,\n \"removeComments\": true,\n \"noLib\": false,\n \"sourceMap\": true,\n \"outDir\": \"./\"\n },\n \"hasValues\": {\n \"hostNode\": true\n }\n}\n```\n### Compiled Code\n\nSo given the `tsconfig.json` above and the following TypeScript:\n\n``` typescript\nhas hostNode: boolean = Boolean(typeof process == \"object\" && process.versions && process.versions.node && process.versions.v8);\n\nif (hostNode) {\n console.log('You are running under node.');\n}\nelse {\n console.log('You are not running under node.');\n}\n```\n\nYou would expect the following to be emitted:\n\n``` js\nconsole.log('You are running under node.');\n```\n\nAs the compiler would replace the symbol of hostNode with the value provided in `tsconfig.json` and then substitute that value in the AST. It would then realise that the one of the branches was unreachable at compile time and then collapse the AST branch and only emit the reachable code.\n","author":{"url":"https://github.com/kitsonk","@type":"Person","name":"kitsonk"},"datePublished":"2015-06-17T16:12:32Z","url":"https://github.com/microsoft/TypeScript/issues/3538"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:25b90013-3189-c094-e9fa-1bd34258d599 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E2D4:38C5CF:5D406A:7A4968:6B00CDD3 |
| html-safe-nonce | b19f0643d974147fbdd2dc6d30e0027aae32d942445c10dad7cc8989a0a3f935 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFMkQ0OjM4QzVDRjo1RDQwNkE6N0E0OTY4OjZCMDBDREQzIiwidmlzaXRvcl9pZCI6Ijc1NDE5MTI5MTUxNTkzMzg0NTEiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 641cf96d16c350fcf8b234a56e2f9ab96e22c539534d9fe473ea0c428961689f |
| hovercard-subject-tag | issue:89060191 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/3538/issue_layout |
| twitter:image | https://opengraph.githubassets.com/91e322fe29b9e422e5b237e566234a144037beb0445b0ecce121d3a40edfd6b8/microsoft/TypeScript/issues/3538 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/91e322fe29b9e422e5b237e566234a144037beb0445b0ecce121d3a40edfd6b8/microsoft/TypeScript/issues/3538 |
| og:image:alt | Proposal: Conditional Compilation Problem Statement At design time, developers often find that they need to deal with certain scenarios to make their code ubiquitous and runs in every environment a... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | kitsonk |
| hostname | github.com |
| expected-hostname | github.com |
| None | 85bbdfe2b6ba16e234513bc6ceff5d848ef8449820c900692a2b4e67061931e5 |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 4943239a6d2c591325dad6e5c313e1cafda877f6 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width