ide:WebStorm 2022.3.2
安装
安装Node.js
下载安装
首先,下载Node.js,其官网网址为:https://nodejs.org/en/download/。
这里由于我是新手,我就使用LTS长期稳定版来学习。
安装完后在命令行中使用node -v
查看信息。
修改配置
参考文章:https://cloud.tencent.com/developer/article/1834667
参考文章:
首先,使用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
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
参考文章:
使用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', // 要使用的loader
exclude: /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的使用
参考文章:
为了使代码能够兼容不同的浏览器,我们需要使用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: [ // 加载器从后往前执行
{ // 配置bale
loader: "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"
}),
]
}