pic

JavaScript 核心

ES6+ 关键特性

// 解构赋值
const { a, b } = obj;
const [x, y] = arr;

// 展开运算符
const newArr = [...arr, item];
const newObj = { ...obj, key: value };

// 可选链与空值合并
const val = obj?.nested?.prop ?? 'default';

// Promise 异步处理
const fetchData = async () => {
  try {
    const res = await fetch('/api');
    return await res.json();
  } catch (err) {
    console.error(err);
  }
};

// 模块化
import { func } from './module.js';
export const myFunc = () => {};

核心概念

  • 事件循环: 宏任务(setTimeout/I/O) → 微任务(Promise) → 渲染
  • 闭包: 函数记住并访问其词法作用域
  • 原型链: obj.__proto__Constructor.prototypeObject.prototype
  • this 绑定: 默认/隐式/显式(call/apply/bind)/new/箭头函数

TypeScript

基础类型

// 基本类型
let str: string = 'text';
let num: number = 42;
let bool: boolean = true;
let anyVal: any = 'anything';
let unknown: unknown = 'safe any';

// 数组与元组
let arr: number[] = [1, 2, 3];
let tuple: [string, number] = ['age', 25];

// 对象与接口
interface User {
  id: number;
  name: string;
  email?: string; // 可选
  readonly createdAt: Date;
}

// 类型别名
type ID = string | number;
type Callback<T> = (data: T) => void;

// 泛型
function identity<T>(arg: T): T {
  return arg;
}

// 联合与交叉类型
type A = { a: string };
type B = { b: number };
type C = A & B; // 交叉: 必须同时包含
type D = A | B; // 联合: 包含其一

实用工具类型

// 常用工具类型
Partial<T>      // 所有属性可选
Required<T>     // 所有属性必需
Readonly<T>     // 所有属性只读
Pick<T, K>      // 选取部分属性
Omit<T, K>      // 省略部分属性
Record<K, T>    // 键值对映射
ReturnType<T>   // 提取返回类型
Parameters<T>   // 提取参数类型

// 使用示例
interface Config {
  host: string;
  port: number;
  ssl: boolean;
}

type OptionalConfig = Partial<Config>;
type ServerConfig = Pick<Config, 'host' | 'port'>;

NPM / Yarn / PNPM

常用命令

# 安装依赖
npm install           # 安装 package.json 依赖
npm install <pkg>     # 安装到 dependencies
npm install -D <pkg>  # 安装到 devDependencies
npm install -g <pkg>  # 全局安装

# Yarn 对应命令
yarn add <pkg>
yarn add -D <pkg>
yarn global add <pkg>

# PNPM (推荐)
pnpm add <pkg>
pnpm add -D <pkg>
pnpm add -g <pkg>

# 脚本运行
npm run dev
npm run build
npm run test

# 包管理
npm update            # 更新依赖
npm outdated          # 查看过时依赖
npm audit fix         # 修复安全漏洞

package.json 关键字段

{
  "name": "project",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "vue": "^3.4.0"
  },
  "devDependencies": {
    "typescript": "^5.3.0",
    "vite": "^5.0.0"
  },
  "engines": {
    "node": ">=18.0.0"
  }
}

关键字段说明

字段说明
name包名,发布到 npm 时的唯一标识
version语义化版本号 (主版本.次版本.补丁)
type"module" 启用 ES Modules 模式,支持 import 语法
main入口文件路径 (CommonJS),默认 index.js
moduleESM 入口文件路径
exports条件导出,区分 ESM/CJS/开发/生产环境
scripts可执行命令,npm run <name> 调用
dependencies生产依赖,运行时必须
devDependencies开发依赖,构建/测试时使用
peerDependencies对等依赖,要求宿主提供该依赖
optionalDependencies可选依赖,安装失败不报错
engines环境要求 (Node/Yarn 版本)
files发布到 npm 时包含的文件白名单
.npmignore / files控制发布内容,减少包体积
private设为 true 防止意外发布到 npm

exports 条件导出

{
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs",
      "types": "./dist/index.d.ts"
    },
    "./package.json": "./package.json"
  }
}

版本语义

  • ^1.2.3: 兼容 1.x.x (>=1.2.3 <2.0.0)
  • ~1.2.3: 兼容补丁版本 (>=1.2.3 <1.3.0)
  • 1.2.3: 精确版本
  • *: 最新版本

Bun

Bun 是 Node.js 的替代运行时,集 runtime、bundler、test runner 于一体。

核心特性

  • 速度快: 使用 Zig 编写,启动和运行速度极快
  • 内置功能: 内置 bundler、test runner、包管理器
  • 兼容: 支持 Node.js API 和 npm 包

常用命令

# 安装 Bun
curl -fsSL https://bun.sh/install | bash

# 运行脚本
bun run index.ts      # 直接运行 TS,无需编译
bun run dev

# 包管理
bun add <pkg>
bun add -d <pkg>
bun remove <pkg>
bun install           # 比 npm install 快 20-30 倍

# 内置测试
bun test

# 构建
bun build ./index.ts --outdir ./out

# 内置 HTTP 服务器
 bun serve

Bun API

// 内置 HTTP 服务器
Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response('Hello Bun!');
  },
});

// 文件读取 (同步 API,实际为异步优化)
const file = Bun.file('./data.json');
const contents = await file.json();

// 写入文件
await Bun.write('./output.txt', 'content');

Vite

Vite 是下一代前端构建工具,原生 ESM,极速 HMR。

项目创建

# 创建项目
npm create vite@latest my-app -- --template vue-ts
npm create vite@latest my-app -- --template react-ts
npm create vite@latest my-app -- --template vanilla-ts

# 启动开发服务器
cd my-app
npm install
npm run dev

配置 (vite.config.ts)

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';

export default defineConfig({
  plugins: [vue()],
  
  // 路径别名
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
  },
  
  // 开发服务器配置
  server: {
    port: 3000,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      },
    },
  },
  
  // 构建配置
  build: {
    outDir: 'dist',
    sourcemap: true,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['vue', 'vue-router'],
        },
      },
    },
  },
  
  // CSS 配置
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "./src/styles/vars.scss";`,
      },
    },
  },
});

环境变量

# .env
VITE_API_URL=http://api.example.com

# .env.production
VITE_API_URL=https://api.example.com
// 代码中使用
const apiUrl = import.meta.env.VITE_API_URL;

常用插件

// 常用 Vite 插件
import vue from '@vitejs/plugin-vue';
import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';
import compression from 'vite-plugin-compression';

export default defineConfig({
  plugins: [
    vue(),
    visualizer(),          // 包体积分析
    compression(),         // gzip 压缩
  ],
});

现代前端工具链

ESLint + Prettier

# 安装
npm install -D eslint prettier eslint-config-prettier eslint-plugin-vue

# 初始化配置
npx eslint --init
// eslint.config.js
import globals from 'globals';
import pluginJs from '@eslint/js';
import tseslint from 'typescript-eslint';
import pluginVue from 'eslint-plugin-vue';

export default [
  { files: ['**/*.{js,mjs,cjs,ts,vue}'] },
  { languageOptions: { globals: globals.browser } },
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  ...pluginVue.configs['flat/essential'],
  {
    rules: {
      'vue/multi-word-component-names': 'off',
      '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
    },
  },
];

Tailwind CSS

# 安装
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
// tailwind.config.js
export default {
  content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};
/* 在 CSS 入口引入 */
@tailwind base;
@tailwind components;
@tailwind utilities;

性能优化要点

  1. 代码分割: 路由级懒加载 () => import('./views/Home.vue')
  2. Tree Shaking: 使用 ES Modules,避免副作用导入
  3. 资源优化: 图片懒加载、WebP 格式、CDN 分发
  4. 缓存策略: 文件名哈希、HTTP 缓存头
  5. Bundle 分析: rollup-plugin-visualizer 分析体积

调试技巧

// Chrome DevTools
console.table(data);           // 表格输出
console.group('label');        // 分组
console.time('label');         // 计时
console.trace();               // 调用栈

// 条件断点
// 在 Sources 面板设置断点条件: user.id === 123

// 网络面板
// 右键请求 -> Copy -> Copy as fetch/cURL

最后更新: 2026-04-12