typescript学习记录-安装
ide:WebStorm 2022.3.2
安装
安装Node.js
下载安装
参考文章:https://www.bilibili.com/video/BV1Xy4y1v7S2?p=2
首先,下载Node.js,其官网网址为:https://nodejs.org/en/download/。
这里由于我是新手,我就使用LTS长期稳定版来学习。
安装完后在命令行中使用node -v
查看信息。
修改配置
参考文章:https://cloud.tencent.com/developer/article/1834667
参考文章:https://xdr630.blog.csdn.net/article/details/111308202
首先,使用npm config get prefix
来查看当前设置的全局目录所在位置。
然后在node.js安装目录下新建两个文件夹 node_global和node_cache,使用npm config set prefix "目录路径"
,npm config set cache "目录路径"
来设置路径。
npm config set prefix "D:\Program Files (x86)\nodejs\node_global"
npm config set cache "D:\Program Files (x86)\nodejs\node_cache"
然后修改环境变量
修改文件夹权限
由于设置的node_global,node_cache以及后面的node_modules都是在软件安装所在文件夹,在win10中会导致有权限限制而不方便运行。这里需要对这三个文件夹修改权限。(或者把文件夹设置在不受权限影响的地方)
安装typescript
官方网址:https://www.typescriptlang.org/zh/
安装到本地
输入命令npm install typescript
这个时候就会在当前路径下创建一个node_modules文件夹,用来存储对应的包。
安装到全局
使用npm install -g typescript
即可将文件安装到全局中。
安装完后使用tsc
查看ts信息
WebStorm配置
参考文章:https://www.jetbrains.com/help/webstorm/typescript-support.html
先新建一个空白的项目,然后新建一个ts文件。在WebStorm的右下方打开设置选项。
配置node的路径,ts的版本。
重启服务
初始化tsconfig文件
参考文章:https://www.jetbrains.com/help/idea/compiling-typescript-to-javascript.html
1是在命令行中运行tsc --init
生成的文件如下,详细的各种参数。
{"compilerOptions": {/* Visit https://aka.ms/tsconfig to read more about this file *//* Projects */// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. *//* Language and Environment */"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */// "jsx": "preserve", /* Specify what JSX code is generated. */// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. *//* Modules */"module": "commonjs", /* Specify what module code is generated. */// "rootDir": "./", /* Specify the root folder within your source files. */// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */// "types": [], /* Specify type package names to be included without being referenced in a source file. */// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */// "resolveJsonModule": true, /* Enable importing .json files. */// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. *//* JavaScript Support */// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. *//* Emit */// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */// "declarationMap": true, /* Create sourcemaps for d.ts files. */// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */// "sourceMap": true, /* Create source map files for emitted JavaScript files. */// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */// "outDir": "./", /* Specify an output folder for all emitted files. */// "removeComments": true, /* Disable emitting comments. */// "noEmit": true, /* Disable emitting files from a compilation. */// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */// "newLine": "crlf", /* Set the newline character for emitting files. */// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */// "declarationDir": "./", /* Specify the output directory for generated declaration files. */// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. *//* Interop Constraints */// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. *//* Type Checking */"strict": true, /* Enable all strict type-checking options. */// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. *//* Completeness */// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */"skipLibCheck": true /* Skip type checking all .d.ts files. */}
}
或者直接使用WebStorm生成。
生成的文件如下。
{"compilerOptions": {"module": "commonjs","target": "es5","sourceMap": true},"exclude": ["node_modules"]
}
我自己个人使用的配置,参考文章:https://johnsonlee.site/post/develop-a-library-based-typescript/
{"compilerOptions": {"module": "ES6", /* 项目模块类型 */"target": "ES6", /* 编译目标 */"strict": true, /* 启用严格模式 */"noEmitOnError": true,"alwaysStrict": true,"allowJs": true, /* 是否允许编译js代码 */"checkJs": true, /* 检查js代码错误 */"outDir": "./test", /* 编译输出目录 */"sourceMap": true},"include": ["src"],"exclude": ["node_modules", "dist", "test"]
}
具体的ts配置信息可以在https://www.typescriptlang.org/tsconfig中查询到。
这样,每次按照下面文件执行都可生成对应的js文件。
运行后
TypeScript Debug
参考文章:https://www.jetbrains.com/help/webstorm/running-and-debugging-typescript.html
参考文章:https://www.jetbrains.com/help/idea/configuring-javascript-debugger.html
参考文章:https://www.jetbrains.com/help/idea/run-debug-configuration-javascript-debug.html
按照配置JavaScript 调试器中的描述配置内置调试器。
URL:指定引用要调试的 JavaScript 的 HTML 文件的 URL 地址。对于本地调试,输入格式为http://localhost:<built-in server port> /<project root>
的URL 。
Browser:从此列表中,选择 Chrome 或您的应用程序将在其中调试的 Chrome 系列中的其他浏览器。
Ensure breakpoints are detected when loading scripts:选中此复选框以确保立即命中页面加载时执行的代码中的断点。请注意,这可能会减慢初始页面加载速度。(这里我没有勾选主要是因为我不是做js,主要是做ts的debug,ts可以直接在代码中断点。)
将 TypeScript 代码编译成 JavaScript,在 TypeScript 代码中配置和设置断点,在对应的js文件中运行debug。
运行debug后
安装webpack
参考文章:https://www.bilibili.com/video/BV1Xy4y1v7S2?p=10
参考文章:https://juejin.cn/post/7077490951186284557
package.json
在项目根目录下执行npm init -y
来生成package.json。
生成的文件如下。
{"name": "untitled","version": "1.0.0","description": "","main": "index.js","directories": {"test": "test"},"scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "ISC"
}
或者直接使用WebStorm生成。
生成的文件如下。
{"name": "untitled","version": "1.0.0","dependencies": {}
}
下载构建工具
参考文章:https://www.jetbrains.com/help/webstorm/using-webpack.html
参考文章:https://www.cnblogs.com/wuqilang/p/15419778.html
使用npm i -D webpack webpack-cli typescript ts-loader
来下载对应工具。
webpack:构建工具webpack
webpack-cli:webpack的命令行工具
typescript:ts的编译器
ts-loader:ts加载器,用于在webpack中编译ts文件
装完后会自动配置安装信息到package.json,同时生成package-lock.json。
{"name": "untitled","version": "1.0.0","description": "","main": "index.js","directories": {"test": "test"},"scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "ISC","devDependencies": {"ts-loader": "^9.4.2","typescript": "^4.9.5","webpack": "^5.75.0","webpack-cli": "^5.0.1"}
}
webpack.config.js
手动创建webpack.config.js。在里面填入配置信息。
//引入一个包
const path = require('path')//webpack中所有的配置信息都应该写在module.exports中
module.exports = {mode: 'none',entry: './src/index.ts', // 指定入口文件output: {path: path.resolve(__dirname, 'dist'), // 指定打包文件的目录filename: 'bundle.js' // 打包后文件的名称},// 指定webpack打包时要使用的模块module: {// 指定loader加载的规则rules: [{test: /\.ts$/, // 指定规则生效的文件:以ts结尾的文件use: 'ts-loader', // 要使用的loaderexclude: /node-modules/ // 要排除的文件}]},// 设置哪些文件类型可以作为模块被引用resolve: {extensions: ['.ts', '.js']}
}
在package.json中加上"build": "webpack"
命令。
然后运行npm run build即可构建。
webpack中常用的插件
html-webpack-plugin
打包时自动创建html文件,并自动引入js文件。使用npm i -D html-webpack-plugin
下载。
同理,在package.json中多出该插件的配置信息。
配置webpack.config.js
然后运行npm run build
设置自定义模板
现在src下面创建一个html模板。
修改webpack.config.js
这样,生成的页面即是模板页面了。
webpack-dev-server
热更新,使用npm i -D webpack-dev-server
下载。
在package.json中加上start命令:"start": "webpack serve --open chrome.exe"
clean-webpack-plugin
在build前清空dist目录所有文件,避免旧文件的遗留,使用npm i -D clean-webpack-plugin
下载。
在package.json引入
babel的使用
参考文章:https://www.cnblogs.com/wuqilang/p/15419778.html
为了使代码能够兼容不同的浏览器,我们需要使用babel工具(与webpack结合一起使用)
安装
npm i -D @babel/core @babel/preset-env babel-loader core-js
其中:
- @babel/core:babel的核心工具
- @babel/core:babel的核心工具
- @babel/preset-env:babel的预设环境
- babel-loader:babel与webpack结合的工具
- core-js:模拟js运行环境,使老版本的浏览器支持新版es语法(比如Promise在ie11中不支持,添加corejs配置会引入corejs中封装的Promise)
修改webpack配置文件,添加babel配置
webpack.config.js最终配置文件
// 引入一个包
const path = require('path');
// 引入html插件
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 引入clean插件
const { CleanWebpackPlugin } = require('clean-webpack-plugin');//webpack中所有的配置信息都应该写在module.exports中
module.exports = {mode: 'none',entry: './src/index.ts', // 指定入口文件output: {path: path.resolve(__dirname, 'dist'), // 指定打包文件的目录filename: 'bundle.js' // 打包后文件的名称// environment: { arrowFunction: false } // 告诉webpack打包后的【立即执行函数】不使用箭头函数(新版的webpack不支持ie11,如果需要打包后的代码支持ie11需要加上该配置)},// 指定webpack打包时要使用的模块module: {// 指定loader加载的规则rules: [{test: /\.ts$/, // 指定规则生效的文件:以ts结尾的文件use: [ // 加载器从后往前执行{ // 配置baleloader: "babel-loader", // 指定加载器options: { // 设定参数presets:[ // 设置预定义的环境["@babel/preset-env", // 指定环境插件{ // 配置信息targets:{"chrome": "58", "ie":11 }, // 要兼容的目标浏览器及版本"corejs": "3", // 指定corejs的版本(根据package.json中的版本,只写整数)useBuiltIns: "usage" // 使用corejs的方式,'usage'表示按需加载}]]}},'ts-loader' // 要使用的loader],exclude: /node-modules/ // 要排除的文件}]},// 设置哪些文件类型可以作为模块被引用resolve: {extensions: ['.ts', '.js']},// 配置webpack插件plugins: [new CleanWebpackPlugin(),new HtmlWebpackPlugin({// title: "这是一个自定义的title"template: "./src/index.html"}),]
}
typescript学习记录-安装相关推荐
- TypeScript学习记录
TypeScript学习记录 vscode设置自动编译 首先使用tsc --init 生成tsconfig.json配置文件 (可以根据需要修改设置) 终端->运行任务->typescri ...
- onlyoffice学习记录-安装与Demo运行
onlyoffice 安装与运行 公司项目需要导入自定义表单然后分发给不同人去填写,然后再搜集汇总,于是便研究了在线协作文档开源框架onlyoffice.发现网络上这个并没有很详细的技术文档,于是对照 ...
- Ruby学习记录 - 安装Ruby
0x00 下载 一直想学习一下Ruby,要问原因呢..听说学Ruby的妹子很多.. 于是兴致勃勃的去买了一门 <Ruby基础编程(第四版)> 研究一下. 首先我们需要下载Ruby,地址 : ...
- typescript学习记录-练习项目-贪食蛇
参考文章:https://www.bilibili.com/video/BV1Xy4y1v7S2?p=22 项目搭建 将之前的package.json,tsconfig.json,webpack.co ...
- ubuntu的学习记录-安装vmtols,更换软件源,开启远程服务
ubuntu内部配置 vmaretools的安装,方便和主机文件的共享 更换软件源,提高apt工具的下载效率: ssh服务的安装与启用,方便远程登陆 vmaretools的安装,方便和主机文件的共享 ...
- [学习记录] macOS下的Nginx安装 Nginx基本知识
[学习记录] macOS下的Nginx安装 && Nginx基本知识 一. 安装相关 1. 安装:直接通过brew安装即可 2. 启动: 3. 成功运行判断: 4. 改端口号:由于80 ...
- 【学习记录】macOS的Redis安装及基本使用
[学习记录]macOS的Redis安装及基本使用 一. Redis的安装与启动 二. 简单使用 ① 尝试插入第一个key-value ② Redis的数据类型与基本使用 字符串 列表 字典(哈希表) ...
- Typescript 学习笔记一:介绍、安装、编译
前言 整理了一下 Typescript 的学习笔记,方便后期遗忘某个知识点的时候,快速回忆. 为了避免凌乱,用 gitbook 结合 marketdown 整理的. github地址是:ts-gitb ...
- LRS+XAPI教育学习记录(安装lrs,以及用xapi传输数据到lrs)
此LRS團隊出了最新版的LRS,是node寫的.運行速度是本文寫的這個版本的無數倍,待我整理好再發出來. 关于lrs跟xapi国内基本用的少,质料基本都是英文的,中文的也就只有繁体的一些少少的资料.新 ...
最新文章
- Springboot的部分依赖及作用
- c语言字符运算 =,C语言运算符
- SAP UI5 jQuery.sap.getModulePath 的工作原理
- phpnow升级php版本 php-5.2.14-Win32升级至5.3.5
- springboot 获取bean_3W 字的 Spring Boot 超详细总结
- selenium使用webdriver新开标签页
- 计算机名称 steam,Steam电脑配置排名:前19名都是N卡
- 开源工具kettle中Job流程的理解
- 华为机试HJ10:字符个数统计
- 【Oracle】恢复重做日志组
- Linux添加1G虚拟内存,Linux下怎样增加虚拟内存
- PdfJS使用的一些说明
- 台式计算机电源机箱维修,终于理会电脑电源故障的维修方法
- 计算QPSK/16QAM/64QAM信号OFDM调制后PAPR
- 复习用vue写tabbar
- (2)安装配置开发工具-JsDroid引流脚本混合式开发技术系列教程By飞云脚本学院
- 互斥事件的概念和公式_相互独立事件与互斥事件的区别
- 编译原理课程设计c语言,编译原理课程设计心得体会
- 项目助理是打杂的吗_应届生如何着手准备应聘产品助理?
- 深度学习之tensorflow:tensorflow-cpu;win10+gtx1050ti+tensorflow-gpu搭建过程以及问题解决
热门文章
- 亚马逊卖家站外引流的方式——TikTok
- python创建一个列表_Python创建一个元素都为0的列表实例
- Java Web 03 — JDBC_02(数据库连接池_C3P0_Druid、JdbcTemplate)
- android设计题,《Android程序设计》期末试题A(答案)
- Web3j签名与验签
- 推荐一个计算机类电子书下载网站:皮皮书屋
- 获得marginLeft
- 【Verilog基础】定点小数的乘法运算
- 什么叫异步通信?同步通信与异步通信的区别是什么?
- 2021年高考语文咸宁查询成绩,2021年咸宁高考状元是谁分数多少分,历年咸宁高考状元名单...