• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

typescript---配置类相关内容(十五)

武飞扬头像
明天变强一点就好
帮助1

tsconfig.json文件

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

    /* Projects */
    /* TS编译器在第一次编译之后会生成一个存储编译器信息的文件,第二次编译会在第一编译基础上进行增量编译,可以提高编译的速度*/
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    /*启用允许Typescript项目与项目引用一起使用的约束 */
    // "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. */
    /*减少Type自动加载的项目数 */
    // "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. */
    /*TS需要引用的库,即声明文件,es5默认引用dom es5 scripthost,如需要使用es高级版本特性,通常都需要进行配置,如es8的数组新特性需要引入"ES2019.Array" */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    /*指定生成的JSX代码 */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    /*启用对TC39第二阶段草稿装饰器的实验支持 */
    "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    /*为源文件中的修饰声明发出设计类型元数据 */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    /*指定针对React JSX emit时使用JSX工厂函数 */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    /* 指定针对React JSX emit时用于片段的JSX片段引用*/
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    /*指定使用JSX:react JSX*时用于导入JSX工厂函数的模块说明符 */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    /*指定为createElement调用的对象,这仅适用针对react JSX emit的情况 */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    /*禁用包含任何库文件  包括默认库  d   ts */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    /*发出符合ECMAScript标准的类字段 */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    /*控制用于检测模块格式JS文件的方法 */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    /*生成代码的模板标准 可选es6模式  amd  umd等等 */
    "module": "commonjs",                                /* Specify what module code is generated. */
    /*指定输出文件目录(用于输出),用于控制输出目录结构 */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    /*模块解析策略,ts默认用node解析策略,即相对的方法导入 */
    // "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. */
    /*路径映射,相对于baseUrl */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    /*将对各目录放在一个虚拟目录下,用于运行时,即编译后引入文件的位置可能发生变化,这也设置可以虚拟src和out在同一个目录下,不用去改变路径也不会报错 */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    /*声明文件目录,默认时node_modules/@types */
    // "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. */
    /*允许在模块中全局变量的方式访问umd模块 */
    // "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. */
  }
}

学新通

使用rollup打包TS文件

安装依赖

  • 全局安装rollup
npm install rollup -g
  • 安装Typescript
npm install typescript -D
  • 安装Typescript转换器
npm install rollup-plugin-typescript2 -D
  • 安装代码压缩插件
npm install rollup-plugin-terser -D
  • 安装rollupweb服务器
npm install rollup-plugin-serve -D
  • 安装热更新
npm install rollup-plugin-livereload -D
  • 安装配置环境变量用于区分本地和生产
npm install cross-env -D

步骤

安装依赖

创建package.json文件

npm init -y
{
  "devDependencies": {
    "cross-env": "^7.0.3",
    "rollup-plugin-livereload": "^2.0.5",
    "rollup-plugin-serve": "^2.0.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "^0.32.1",
    "typescript": "^4.7.4"
  },
  "name": "rollupproject",
  "version": "1.0.0",
  "main": "rollup.config.js",
  "dependencies": {
    "anymatch": "^3.1.2",
    "acorn": "^8.8.0",
    "ansi-styles": "^3.2.1",
    "binary-extensions": "^2.2.0",
    "chalk": "^2.4.2",
    "chokidar": "^3.5.3",
    "braces": "^3.0.2",
    "buffer-from": "^1.1.2",
    "commander": "^2.20.3",
    "color-name": "^1.1.3",
    "commondir": "^1.0.1",
    "color-convert": "^1.9.3",
    "escape-string-regexp": "^1.0.5",
    "fill-range": "^7.0.1",
    "cross-spawn": "^7.0.3",
    "estree-walker": "^2.0.2",
    "fs-extra": "^10.1.0",
    "find-cache-dir": "^3.3.2",
    "find-up": "^4.1.0",
    "function-bind": "^1.1.1",
    "glob-parent": "^5.1.2",
    "graceful-fs": "^4.2.10",
    "has": "^1.0.3",
    "has-flag": "^3.0.0",
    "is-binary-path": "^2.1.0",
    "is-extglob": "^2.1.1",
    "is-core-module": "^2.10.0",
    "is-glob": "^4.0.3",
    "isexe": "^2.0.0",
    "js-tokens": "^4.0.0",
    "jest-worker": "^26.6.2",
    "is-number": "^7.0.0",
    "jsonfile": "^6.1.0",
    "locate-path": "^5.0.0",
    "livereload": "^0.9.3",
    "livereload-js": "^3.4.1",
    "make-dir": "^3.1.0",
    "merge-stream": "^2.0.0",
    "mime": "^3.0.0",
    "normalize-path": "^3.0.0",
    "opener": "^1.5.2",
    "p-limit": "^2.3.0",
    "opts": "^2.0.2",
    "p-locate": "^4.1.0",
    "p-try": "^2.2.0",
    "path-exists": "^4.0.0",
    "path-key": "^3.1.1",
    "path-parse": "^1.0.7",
    "pkg-dir": "^4.2.0",
    "randombytes": "^2.1.0",
    "rollup": "^2.77.2",
    "picomatch": "^2.3.1",
    "readdirp": "^3.6.0",
    "semver": "^6.3.0",
    "safe-buffer": "^5.2.1",
    "resolve": "^1.22.1",
    "serialize-javascript": "^4.0.0",
    "shebang-command": "^2.0.0",
    "shebang-regex": "^3.0.0",
    "source-map": "^0.6.1",
    "terser": "^5.14.2",
    "source-map-support": "^0.5.21",
    "supports-color": "^5.5.0",
    "supports-preserve-symlinks-flag": "^1.0.0",
    "to-regex-range": "^5.0.1",
    "tslib": "^2.4.0",
    "universalify": "^2.0.0",
    "which": "^2.0.2",
    "ws": "^7.5.9"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    /*生成环境*/
    "build": "cross-dev NODE_ENV=production rollup -c",
    /*开发环境    删除-w,可以避免热更新一直打开浏览器问题*/
    "dev": "cross-dev NODE_ENV=development rollup -c -w"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}


学新通

创建目录和配置文件

  • 创建src文件夹
  • 创建public文件夹
  • 创建rollup.config.js文件
  • 配置 rollup.config.js文件
import path from 'path'
import ts2 from "rollup-plugin-typescript2"
import serve from 'rollup-plugin-serve'
import livereload from 'rollup-plugin-livereload'
import {terser} from "rollup-plugin-terser"
export default {
  input: "./src/index.ts",
  output: {
    file: path.resolve(__dirname,"./dist/index.js"),
    // 启用压缩后,代码阅读性差,这个开启src,方便代码阅读
    sourcemap: true,
    format: 'umd'
    
  },
  plugins: [
    ts2(),
    livereload(),
    terser(),
    serve({
      open: true,
      port: 8080,
      openPage: '/public/index.html'
    })
  ]
}
学新通

创建ts配置文件

tsc --init
  • 自动创建tsconfig.json
{
  "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": "ES6",                                /* 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. */
  }
}

学新通

使用webpack打包TS文件

安装依赖

安装webpack环境

npm i webpack webpack-cli webpack-dev-server -D

安装Typescript

npm install typescript -D

编译TS

npm install ts-loader -D

热更新服务

npm install webpack-dev-server -D

HTML模板

npm install html-webpack-plugin -D

步骤

安装依赖

创建配置package.json

npm init -y
  • 修改package.json
{
  "name": "webpackproject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "dev": "webpack serve --open"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^5.5.0",
    "ts-loader": "^9.3.1",
    "typescript": "^4.7.4",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.9.3"
  }
}

学新通

创建初始文件夹

  • 创建tsconfig.json文件
npm --init

配置配置文件

  • 配置webpack.config.js
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')


module.exports = {
  entry: "./src/index.ts",

  output: {
    path: path.resolve(__dirname,"dist"),
    filename: "index.js"
  },

  module: {
    rules: [
      {test: /\.ts$/,use: "ts-loader",exclude: /node_modules/}
    ]
  },
  mode: "development",
  resolve: {
    extensions: [".ts",".js"]
  },
  plugins: [
    new htmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
}
学新通

TS描述文件声明

  • TS作为JS的超集,在开发过程中不可避免要引用其他的第三方的JS库,虽然通过直接引用可以调用库的类和方法,但是却无法使用TS诸如类型检查等特性功能,为了解决这个问题,需要将这些库里的函数和方法去掉后只保留导出类型声明,而产生了一个描述JS库和模块信息的声明文件,通过这个声明文件,就可以借用TS的各种特性来使用库文件

直接使用js库

  • 第三方JS文件
./public/js/test.js
const userName = "法外狂徒张三"
function add(num2,num3){
	return num2   num3
}
  • ts使用方
./src/test.d.ts
 declare let userName: string
 declare function add(num2: number,num3: number): number

./src/index.ts
console.log(userNamer) // 法外狂徒张三
console.log(add(10,30)) // 40

第三方库的声明文件

  • 上面直接引入的第三方库,格式复杂,工作效率低
  • 可以直接使用第三方库的声明文件访问
    • https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types
    • https://www.typescriptlang.org/dt/search?search=

安装VUE3_ts并与vue3_js对比

创建vue_js项目

vue create 项目名称

创建vue_ts项目

vue create 项目名称

创建vue_vite_ts项目

npm init vite@latest

安装 react_ts环境并于react_js对比

创建react_js项目

npx create-react-app 项目名

创建react_ts项目

npx create-react-app 项目名 --template typescript

创建react_vite_ts项目

npm init vite@latset
```

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgghgie
系列文章
更多 icon
同类精品
更多 icon
继续加载