In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "Why to compile Typescript with Babel" related knowledge, editor through the actual case to show you the operation process, the method of operation is simple and fast, practical, I hope that this "Why to compile Typescript with Babel" article can help you solve the problem.
Typescript extends the syntax and semantics of types to javascript, making js code type safe at the statically typed language level. Type unsafe problems that can only be found at run time can now be found during compilation, so more and more large projects choose to write in typescript. In addition, typescript can also cooperate with ide to do better smart tips, which is also a reason to use typescript.
Type safety: if a variable of a type is assigned to a value of an incompatible type, it is type unsafe, and if an object of a type calls a method that it does not have, it is also type unsafe. On the contrary, it is type safety. Type safety means that the assignment of variables and the function calls of objects are all within the scope of type support.
At first, typescript code can only be compiled with its own tyepscript compiler (tsc). Different versions of typescript code need to be compiled with different versions of tsc. Configure tsconfig.json to specify how to compile.
But there is a problem with tsc compiling ts code to js:
Tsc does not support many grammars that are still in the draft stage, which are supported by the babel plug-in, so the toolchain of many projects compiles ts code once in tsc and then by babel. This way the compilation link is long and the generated code is not concise enough.
Therefore, typescript works with the babel team to support the compilation of typescript in babel7, and the compilation of ts syntax can be specified through plug-ins. For example, it is used in api:
Const parser = require ('@ babel/parser'); parser.parse (sourceCode, {plugins: ['typescript']})
This plug-in is the result of a year of cooperation between the typescript team and the babel team.
But does this plug-in really support all typescript code? The answer is no.
Let's take a look at which ts grammars babel doesn't support and why.
Can babel compile all typescript code?
The compilation process of babel is as follows:
Parser: parse the source code into ast
Traverse: traversing ast, generating scope information and path, calling various plug-ins to transform ast
Generator: print the converted ast into object code and generate sourcemap
The compilation process of typescript compiler goes like this:
Scanner + parser: the process of word segmentation and assembly of ast, from source code to ast
Binder + checker: generate scope information, perform type derivation and check
Transform: converts ast after type checking
Emitter: print ast into object code, generate sourcemap and type declaration files (according to configuration)
In fact, the compilation phase of babel is similar to that of tsc, except that tsc has an extra checker, and there is no difference between the rest.
Parser of babel corresponds to scanner + parser of tsc
The traverse phase of babel corresponds to the binder + transform of tsc
Generator of babel corresponds to emitter of tsc
So can babel-based plug-ins implement checker in traverse?
The answer is no.
Because the type check of tsc needs to get the type information of the whole project, it needs to introduce the type and merge the namespace, enum, interface of multiple files, while babel is compiled by a single file and will not parse the information of other files. So you can't do the same type checking as tsc.
One is to parse multiple files in the compilation process, and the other is that the compilation process is only for a single file, and the difference in the process causes babel to be unable to check the type of tsc.
So how does babel compile typescript?
In fact, babel can only parse ts code into ast, will not do type checking, will directly remove the type information, and then print into the object code.
This leads to some ts syntax that babel does not support:
Const enum does not support it. Const enum replaces a reference to enum with a specific value during compilation, which requires parsing type information, which babel does not parse, so it is not supported. You can use the appropriate plug-in to convert const enum to enum.
Partially supported by namespace. Cross-file merging of namespace is not supported, and the export of non-const values is not supported. This is also because babel does not parse type information and is single-file compilation.
The above two are not supported because of the different compilation methods.
Export = import = this ts-specific syntax is not supported and can be converted to esm through plug-ins
If jsx compilation is enabled, then
These four are ts grammars that babel does not support, but they do not have much impact. It would be nice to use these features.
Conclusion: babel cannot compile all typescript code, but all but two features of namespace can be compiled.
Babel can compile typescript code, so why compile it with babel?
Why compile typescript code with babel?
There are three main advantages of babel compiling typescript code:
The product is smaller.
Tsc
How does tsc configure the compilation target?
Configure target,target in compilerOptions to set the target language version
{compilerOptions: {target: "es5" / / es3, es2015}}
How does typescript introduce polyfill?
Introduce core-js into the entry file.
Import 'core-js'
Babel7
How does babel7 configure the compilation target?
Specify targets in preset-env, directly specify the target runtime environment (browser, node) version, or specify a query string, and browserslist will find out the specific version.
{presets: [["@ babel/preset-env", {targets: {chrome: 45}}]} {presets: [["@ babel/preset-env" {targets: "last 1 version, > 1% dead not dead"}]}
How does babel7 introduce polyfill?
It is also configured in @ babel/preset-env. In addition to specifying targets, you should also specify which polyfill to use (corejs2 or corejs3) and how to introduce it (entry is introduced at the entrance, and each module of usage is introduced separately).
{presets: [["@ babel/preset-env", {targets: "last 1 version, > 1% last not dead", corejs: 3, useBuiltIns: 'usage'}]]}
In this way, syntax conversion and api polyfill can be done based on @ babel/compat-data data:
First find out the supported version of the target environment according to targets, and then filter the supported features from all the features according to the version of the target environment, and the rest are unsupported features. Only these features can be converted and polyfill.
And babel can also use @ babel/plugin-transform-runtime to convert the import of the global corejs into a modular introduction.
Obviously, compiling typescript with babel has two advantages in terms of production:
Ability to do more accurate on-demand compilation and polyfill with smaller product size
Can use plug-ins to turn polyfill into a modular introduction without polluting the global environment
From the product point of view, babel wins.
Supported language features
Typescript supports many features of es by default, but does not support features that are still in the draft stage. Babel's preset-env supports all standard features, and more features that are not yet standard can be supported through proposal.
{plugins: ['@ babel/proposal-xxx'], presets: ['@ babel/presets-env', {...}]}
In terms of supported language features, babel wins.
Compilation speed
Tsc will do type checking during compilation. Type checking needs to integrate the type information of multiple files. It is time-consuming to derive the type of AST, while babel does not do type checking, so the compilation speed will be much faster.
In terms of compilation speed, babel wins.
In short, in terms of the size of the compilation product (primary), supported language features, and compilation speed, babel wins.
However, babel does not do type checking, so how can type checking be done?
The combination of babel and tsc
Babel can be compiled to produce smaller products, with faster compilation speed and more feature support, so we chose to compile typescript code with babel. But type checking is also required. You can use a command in npm scripts:
{"scripts": {"typeCheck": "tsc-- noEmit"}}
This allows you to perform a separate npm run typeCheck when type checking is needed, but it's best to do another mandatory type check in git commit's hook (through husky configuration).
This is the end of the introduction to "Why to compile Typescript with Babel". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.