In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about the modularization and construction from JavaScript to TypeScript, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
The benefit of TypeScript is static type checking, so before moving from JavaScript to TypeScript, it's important to realize that adding type definitions brings additional effort, which is a necessary price. However, these costs are worth the benefits of static type checking. Of course, TypeScript allows no types to be defined or all types to be defined as any, but if you do so, most of the static checking capabilities that TypeScript brings will be useless, in other words, there is no need to use TypeScript.
Modularization
One more thing to pay attention to before conversion is modularity. In the early days of JavaScript code, basically one or more JavaScript scripts per HTML page, there was little concept of modularity in JavaScript code at that time. However, with the rise of Web 2.0, a large number of work moves from the back end to the front end, JavaScript programs become more and more complex, modularization becomes a rigid requirement, and a large number of modular frameworks follow, among which the more famous ones are RequestJS and the AMD standard brought by SeaJS, and the CMD standard brought by SeaJS. With the rise of Node.js and the full stack of JavaScript, there is a CommonJS standard. Then came the widely used SystemJS. Of course, there is the modular standard of ES6, although so far Node.js and most browsers do not support it.
TypeScript itself supports two modularization methods, one is a small extension of ES6's module, and the other is to emulate the namespace of C # itself before the release of ES6. Most scenarios that use command space can be replaced by the ES6 modularization standard. Let's first take a look at the difference between the two modular approaches.
Namespace
After the TS script written in the command space is translated into JS, the frame can be loaded without any module and can be used directly in the page. Unfortunately, JS programs escaped in this way cannot be used directly in Node.js. Because tsc does not generate modules.exports objects and require statements for modules that can be in the form of namespaces.
There is one exception. Translate all .ts files into a .js, suppose it is called all.js, then it can be run through node all. In this case, there is no need for any module import and export.
However, in a browser environment, it is feasible to introduce generated .js files in strict dependency order. Early did not use a modular JS file to use the "namespace" form of modular writing, and even hundreds of lines of large JS source file, split into a number of small TS files, and then through tsc-outfile output a single JS file to use, so that you can achieve modular refactoring, but not to change the original HTML (or other dynamic page file) code.
It is also important to note that when a single output file is specified, TypeScript does not check for dependencies between modules through code logic. By default, it translates .ts files in alphabetical order of file names, unless dependencies are explicitly specified in the source file.
ES6 module
When TypeScript uses ES6 module syntax to achieve modularization, tsc allows you to specify which modular framework the generated .js will be applied to through the module parameter. The default is commonjs, and other common ones include amd, system, and so on.
Obviously, if the original JS program uses the AMD framework, when converting to TS, you can use the ES6 module to write, and through tsc-module amd to output the corresponding JS file, also do not need to modify the original page file.
However, if the original JS file does not use any module framework, it will be a bit troublesome to convert to TS code written in the ES6 module. In this case, even if it is built as a single output file, it still requires the support of a modular framework, such as define and require for AMD, or API support for System.
To avoid introducing a modular framework, consider exporting JS to the commonjs standard, and then packaging all the generated JS into a single file through Webpack. Now that Webpack is used here, the build configuration can be more flexible, because Webpack can specify multiple entry, can have multiple output, it will be through import. Translated into require (...) Automatically check for dependencies. And Webpack can also use ts-loader to process .ts files directly without first using tsc for translation. If you use a higher version of ECMAScript syntax in TS, such as async/await, you can also add a layer of processing through babel-loader. Very flexible.
But there is often a problem here: all the definitions in the generated .js are not in the global scope, so how do you use the content defined in the script after it is introduced into the web page? This requires the help of the global object window--. There is no need to consider the global object global of Node.js here, because it is generally introduced in a modular way under Node.js, and there is no need to inject anything into the global object.
The method of injecting objects (or functions, values, etc.) into window is also simple, in two steps: declaring and assigning values, such as:
Import MyApi from ". / myapi"; declare global {interface Window {mime: MyApi;}} window.mime = new MyApi ()
Commonly used build configuration
We used the TypeScript namespace in our early projects, but recently almost all of them have reconstructed the ES6 module approach. Because the async function is used, TypeScript is generally configured to output ES2017 code, which is then translated into ES5 code through Babel, and * is packaged and output by Webpack.
Tsconfig.json
{"compilerOptions": {"module": "commonjs", "target": "es2017", "lib": ["dom", "es6", "dom.iterable", "scripthost", "es2017"], "noImplicitAny": false "sourceMap": false}}
When target is es5 or es6, TypeScript has a default lib list, which is detailed in the official documentation. Target is defined as es2017 to support the async function, but there is no default lib list for this configuration, so refer to the lib list used by target es6 in the official documentation and supplement the es2017 type library.
Webpack.config.js
The configuration format of Webpack2 is used here.
Module.exports = {entry: {index: ". / js/index"}, output: {filename: "[name] .js"}, devtool: "source-map", resolve: {extensions: [.ts "]}, module: {rules: [{test: /\ .ts $/ Use: [{loader: "babel-loader", options: {presets: ["es2015", "stage-3"]}} "ts-loader"], exclude: / node_modules/}]}}
Gulp task
If you still use gulp, the task is written like this
Const gulp = require ("gulp"); const gutil = require ("gulp-util"); / / translate JavaScript gulp.task ("webpack", () = > {const webpack = require ("webpack-stream"); const config = require (". / webpack.config.js") Return gulp.src (". / js/**/*.ts") .pipe (webpack (config, require ("webpack")) .on ("error", function (err) {gutil.log (err); this.emit ("end");}) .pipe (gulp.dest (".. / www/js"));})
It is important to note that webpack-stream uses webpack1 by default, and our configuration requires webpack2, so specify a second parameter for it, a specific version of the webpack instance (imported by require ("webpack")).
Required Node module
It is not difficult to summarize the Node modules that need to be installed during the build process from the above build configuration. There are some
Gulp
Gulp-util
Webpack-stream
Webpack
Ts-loader
Typescript
Babel-loader
Babel-core
Babel-preset-es2015
Babel-preset-stage-3
Run .ts directly in the Node.js environment
In Node.js, you can run TypeScript code directly through the ts-node package. All you need to do is add a sentence to the entry code file (.js code, of course)
Require ('ts-node') .register ({/ * options * /})
Or
Require ('ts-node/register')
Since Node.js 7.6 has directly supported async function syntax, even if you use this syntax, you don't have to worry that ts-node translation in memory won't work.
The portal file must still be a .js file, which is a small pity, but there are two good news for users who use Node.js to write build scripts: both gulp and webpack directly support .ts portal (or configuration) files. For example, take gulp as an example, you can define gulpfile.ts (note that the extension is .ts) as follows
Import * as gulp from "gulp"; gulp.task ("hello", () = > {console.log ("hello gulp");})
However, gulp also uses TypeScript through the ts-node module, and the functionality of ts-node depends on typescript, so don't forget to install these two modules.
After reading the above, do you have any further understanding of modularization and construction from JavaScript to TypeScript? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.