JavaScript 项目初始化与基础配置

项目初始化是构建 JavaScript 开发环境的第一步,正确的初始化配置能为后续开发工作奠定坚实基础。

mkdir my-js-project
cd my-js-project

建议:使用小写字母、数字和连字符命名项目,具有描述性。

package.json 是 Node.js 项目的核心配置文件,包含项目信息和依赖管理。

# 快速初始化(使用默认值)
npm init -y

# 推荐:交互式初始化
npm init

交互式方式会引导填写以下字段:

  • name:项目名称
  • version:版本号(建议使用 语义化版本
  • description:项目描述
  • entry point:入口文件(建议为 src/index.js
  • test command:测试命令
  • git repository:Git 仓库地址
  • keywords:关键词
  • author:作者信息
  • license:许可证(如 MIT、Apache-2.0)
mkdir src tests docs
touch src/index.js tests/index.test.js README.md .gitignore
my-js-project/
├── src/                    # 源代码目录
│   ├── index.js            # 主入口文件
│   ├── utils/              # 工具函数
│   │   ├── index.js
│   │   └── helpers.js
│   ├── components/         # 组件代码
│   └── config/             # 配置项
├── tests/                  # 测试目录
│   ├── setup.js
│   ├── utils/
│   │   └── helpers.test.js
│   └── index.test.js
├── docs/                   # 文档目录
│   ├── api.md
│   └── guide.md
├── dist/                   # 构建输出(自动生成)
├── coverage/               # 测试覆盖率(自动生成)
├── node_modules/           # 依赖包目录(自动生成)
├── .gitignore              # Git 忽略配置
├── package.json            # 项目配置文件
├── package-lock.json       # 依赖锁文件
├── .eslintrc.js            # ESLint 配置
├── .prettierrc             # Prettier 配置
├── .editorconfig           # 编辑器统一配置
├── jest.config.js          # Jest 测试配置
├── babel.config.js         # Babel 配置
└── README.md               # 项目说明文档
{
  "name": "my-js-project",
  "version": "1.0.0",
  "description": "A modern JavaScript project template",
  "main": "dist/index.js",
  "type": "module",
  "scripts": {
    "start": "node dist/index.js",
    "dev": "nodemon src/index.js",
    "build": "babel src --out-dir dist",
    "test": "jest",
    "lint": "eslint src tests",
    "format": "prettier --write \"src/**/*.js\" \"tests/**/*.js\""
  },
  "keywords": ["javascript", "es6", "modern"],
  "author": "Your Name <[email protected]>",
  "license": "MIT",
  "engines": {
    "node": ">=16.0.0",
    "npm": ">=8.0.0"
  }
}
"type": "module"
  • 使用 "module" 开启 ES6 模块支持。
  • 使用 "commonjs" 或省略则为 CommonJS 模式。
"engines": {
  "node": ">=16.0.0",
  "npm": ">=8.0.0"
}

指定 Node 和 npm 最小版本,有助于团队统一环境。

常用脚本命令:

"scripts": {
  "start": "node dist/index.js",
  "dev": "nodemon src/index.js",
  "build": "babel src --out-dir dist",
  "build:watch": "babel src --out-dir dist --watch",
  "clean": "rm -rf dist coverage",
  "test": "jest",
  "test:watch": "jest --watch",
  "test:coverage": "jest --coverage",
  "lint": "eslint src tests",
  "lint:fix": "eslint src tests --fix",
  "format": "prettier --write \"src/**/*.js\" \"tests/**/*.js\"",
  "format:check": "prettier --check \"src/**/*.js\" \"tests/**/*.js\"",
  "prepare": "husky install"
}

src/index.js

/**
 * 项目主入口文件
 */
import { greet } from './utils/helpers.js';

const main = () => {
  console.log(greet('JavaScript Project'));
  console.log('项目初始化完成!');
};

if (import.meta.url === `file://${process.argv[1]}`) {
  main();
}

export default main;

src/utils/helpers.js

/**
 * 工具函数集合
 */

export const greet = (name) => {
  if (typeof name !== 'string' || name.trim() === '') {
    throw new Error('Name must be a non-empty string');
  }
  return `Hello, ${name}!`;
};

export const isEven = (num) => {
  if (typeof num !== 'number') {
    throw new Error('Input must be a number');
  }
  return num % 2 === 0;
};

src/utils/index.js

export * from './helpers.js';

.gitignore

# 依赖与构建产物
node_modules/
dist/
build/
coverage/

# 日志
*.log
logs/

# 环境变量
.env*
*.env.*

# 编辑器配置
.vscode/
.idea/
*.swp
*.swo

# 操作系统文件
.DS_Store
Thumbs.db

# 其他缓存和运行时数据
.npm
.eslintcache
pids
*.pid

README.md

# My JavaScript Project

## 简介

现代化 JavaScript 项目模板,预配置开发环境、测试框架、代码质量工具等。

## 特性

- ✅ 支持 ES6+ 模块
- ✅ ESLint + Prettier 代码规范
- ✅ Jest 单元测试和覆盖率
- ✅ Git hooks 集成
- ✅ 跨平台构建工具链

## 快速开始

### 安装依赖

```bash
npm install
tree -I node_modules

或:

ls -la
npm config list
npm run
node src/index.js

如启用 ES6 模块语法需加参数:

node --experimental-modules src/index.js
npm run dev
npm test
npm run build

确保添加 .js 后缀:

// ✅ 正确
import { greet } from './utils/helpers.js';

// ❌ 错误
import { greet } from './utils/helpers';
node --version
npm --version

建议使用 nvm 管理 Node.js 版本。

项目初始化完成后,可根据需要继续配置开发环境:

  1. 配置 Babel 进行 ES6+ 代码转译
  2. ESLint 和 Prettier 代码质量工具配置
  3. Jest 单元测试框架配置