likes
comments
collection
share

TS的编译环境搭建-webpack和ts-node两种方式

作者站长头像
站长
· 阅读数 2

前言

JavaScript无疑是一门非常优秀的编程语言,也在web端、移动端、小程序端、桌面端以及服务器端被应验着。但是由于历史因素,JavaScript语言本身存在着许多的缺点。比如至今JavaScript也没有加入类型检测这一机制。为了弥补JavaScript类型约束的缺失,很多公司提出了自己的方案,由微软提出的TypeScript(TS)出现在了众人面前。

TS和目前流行的框架结合的就很好,比如Angular、Vue3和React等。

一、初识TS

Github的 的描述是

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

TS的更多知识可以查阅官网

我们可以将TypeScript理解成加强版的JavaScript,TypeScript最终会被编译成JavaScript代码。就像官方说的

  1. 始于JavaScript,归于JavaScript
  2. TypeScript是一个强大的工具,用于构建大型项目
  3. 拥有先进的JavaScript

二、编译环境

TypeScript最终会被编译成JavaScript代码,所以我们需要搭建对应的环境。 要将TS代码编译成JS代码,然后再将JS代码运行在浏览器上。这第一步就需要全局安装TypeScript,通过TypeScript的compiler将代码编译成JS代码。 npm install -g typescript

使用以下命令查看版本 tsc --version

一个简单的例子🌰:


function sum(num1:number,num2:number){
    return num1 + num2
}

const total = sum(10,20)
console.log('---total---',total)

export {}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<script src="./index.ts"></script>
<body>
    
</body>
</html>

在浏览器中打开控制台会发现报错

TS的编译环境搭建-webpack和ts-node两种方式

TS文件不能直接运行在浏览器中,需要编译成JS才行。 在代码所在的目录下运行命令 tsc index.ts

会发现目录下多了一个index.js的文件,将html中的index.ts换成index.js,再去查看控制台

TS的编译环境搭建-webpack和ts-node两种方式

目录是这样的 TS的编译环境搭建-webpack和ts-node两种方式

PS:还有一点需要注意的是须将生成的js文件中关于模块的代码注释

TS的编译环境搭建-webpack和ts-node两种方式

如果要这样编译TS文件就太繁琐了,而且实际开发中,一个项目不止一个TS文件。所以我们不会这样编译TS代码的。实际上,我们可以通过两种不同的方式达到简化编译的效果。 方式一,通过webpack配置TS的编译环境; 方式二,通过ts-node库为TS的运行提供环境。 我们先来看第二种,操作比较简单点,然后重点说说第一种。

2.1 ts-node配置TS运行环境

首先需要安装ts-node npm install ts-node -g 还需要安装相关的依赖tslib和@types/node npm install tslib @types/node -g

然后,就可以通过ts-node来运行TypeScript的代码 ts-node index.ts

一个小例子🌰 TS的编译环境搭建-webpack和ts-node两种方式

2.2 webpack搭建TS环境

一般项目的开发都会使用npm来管理项目的依赖,而且webpack本身也有许多的依赖。所以我们先初始化package.json文件 npm init -y

TS的编译环境搭建-webpack和ts-node两种方式

然后是安装相关依赖 首先是安装TypeScript npm install typescript

之前已经全局安装过typescript,为什么还需要本地安装呢? 因为webpack会在本地查找TypeScript的依赖。

需要tsconfig.json配置文件,针对Typscript的相关配置。通过命令生成文件 tsc --init

生成的tsconfig.json文件

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                         /* Enable incremental compilation */
    "target": "es5",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                                   /* Specify library files to be included in the compilation. */
    // "allowJs": true,                             /* Allow javascript files to be compiled. */
    // "checkJs": true,                             /* Report errors in .js files. */
    // "jsx": "preserve",                           /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "declaration": true,                         /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                      /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                           /* Generates corresponding '.map' file. */
    // "outFile": "./",                             /* Concatenate and emit output to single file. */
    // "outDir": "./",                              /* Redirect output structure to the directory. */
    // "rootDir": "./",                             /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                           /* Enable project compilation */
    // "tsBuildInfoFile": "./",                     /* Specify file to store incremental compilation information */
    // "removeComments": true,                      /* Do not emit comments to output. */
    // "noEmit": true,                              /* Do not emit outputs. */
    // "importHelpers": true,                       /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,                  /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,                     /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                                 /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                       /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                    /* Enable strict null checks. */
    // "strictFunctionTypes": true,                 /* Enable strict checking of function types. */
    // "strictBindCallApply": true,                 /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,        /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                      /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                        /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                      /* Report errors on unused locals. */
    // "noUnusedParameters": true,                  /* Report errors on unused parameters. */
    // "noImplicitReturns": true,                   /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,          /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                  /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
    // "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */

    /* Module Resolution Options */
    // "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                             /* Base directory to resolve non-absolute module names. */
    // "paths": {},                                 /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                              /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                             /* List of folders to include type definitions from. */
    // "types": [],                                 /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,        /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,                    /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,                /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                            /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                               /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                     /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                       /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,              /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,               /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  }
}

npm install ts-loader ts-loader用来解析ts文件,后面用在webapck配置文件中

然后是配置webpack的相关内容 安装webpack及相关依赖 npm install webpack webpack-cli -D npm install webpack-dev-server html-webpack-plugin -D 需要webpack-dev-server来开启服务,html-webpack-plugin的作用是编译后的代码放在html中,用这个插件来配置 template 模板。

完整的webpack配置:

const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
    mode: "development",
    entry: "./src/index.ts",
    output:{
        path: path.resolve(__dirname,"./dist"),
        filename: 'bundle.js'
    },
    resolve:{
        extensions:['.js','.ts','.cjs','.json']
    },
    devServer:{},
    module:{
        rules:[
            {
                test:/\.ts$/,
                loader:'ts-loader'
            },
            {
                test:/\.(png|jpe?g|svg|gif)$/,
                type: 'asset/resource'
            }
        ]
    },
    plugins:[
        new HtmlWebpackPlugin({
            template: './index.html'
        })
    ]
}

代码的运行和打包命令在 package.json 的 script 中

{
  "name": "ts-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "serve": "webpack serve",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "typescript": "^5.3.3"
  },
  "devDependencies": {
    "html-webpack-plugin": "^5.6.0",
    "ts-loader": "^9.5.1",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  }
}

引入图片时需要注意,要写一个类型声明文件,以.d.ts结尾,

// 声明模块
declare module "*.jpeg"
declare module "*.jpg"
declare module "*.png"
declare module "*.svg"
//不加声明文件的话,这里引入会报错
//Cannot find module './img/icon.jpeg' or its corresponding type declarations.
import iconImg from "./img/icon.jpeg"
import { sum } from "./utils/math"

let message = 'Hello TypeScript'
// message = 8888
console.log('---message---',message)

const total = sum(10,20)
console.log('---total---',total)

const imgEl = document.createElement('img')
imgEl.src = iconImg
document.body.append(imgEl)

目录结构:

TS的编译环境搭建-webpack和ts-node两种方式

运行效果:

TS的编译环境搭建-webpack和ts-node两种方式

TS的编译环境搭建-webpack和ts-node两种方式