前端框架与工具开发指南

1. JavaScript 库和框架

1.1 jQuery

// DOM 操作
$(document).ready(function() {
    // 选择器和操作
    $('#myId').addClass('active');
    $('.myClass').hide();
    
    // 事件处理
    $('button').click(function() {
        $(this).toggleClass('active');
    });
    
    // AJAX 请求
    $.ajax({
        url: '/api/data',
        method: 'GET',
        success: function(response) {
            console.log(response);
        },
        error: function(xhr, status, error) {
            console.error(error);
        }
    });
});

1.2 React

// 函数组件
function Welcome({ name }) {
    const [count, setCount] = useState(0);
    
    useEffect(() => {
        document.title = `Count: ${count}`;
    }, [count]);
    
    return (
        <div>
            <h1>Hello, {name}</h1>
            <button onClick={() => setCount(count + 1)}>
                Count: {count}
            </button>
        </div>
    );
}

// 类组件
class Counter extends React.Component {
    state = { count: 0 };
    
    increment = () => {
        this.setState(state => ({
            count: state.count + 1
        }));
    };
    
    render() {
        return (
            <button onClick={this.increment}>
                Count: {this.state.count}
            </button>
        );
    }
}

// React Hooks
function useCustomHook(initialValue) {
    const [value, setValue] = useState(initialValue);
    
    useEffect(() => {
        // 副作用处理
        return () => {
            // 清理函数
        };
    }, [value]);
    
    return [value, setValue];
}

1.3 Vue

<!-- 单文件组件 -->
<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="increment">Count: {{ count }}</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue!',
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  },
  mounted() {
    console.log('Component mounted')
  }
}
</script>

<!-- Vuex 状态管理 -->
<script>
import { mapState, mapActions } from 'vuex'

export default {
  computed: {
    ...mapState(['count'])
  },
  methods: {
    ...mapActions(['increment'])
  }
}
</script>

<!-- Vue Router -->
<script>
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})
</script>

1.4 Angular

// 组件
@Component({
  selector: 'app-root',
  template: `
    <h1>{{ title }}</h1>
    <button (click)="increment()">Count: {{ count }}</button>
  `
})
export class AppComponent {
  title = 'My App';
  count = 0;
  
  increment() {
    this.count++;
  }
}

// 服务
@Injectable({
  providedIn: 'root'
})
export class DataService {
  private apiUrl = 'api/data';
  
  constructor(private http: HttpClient) {}
  
  getData() {
    return this.http.get(this.apiUrl);
  }
}

// 指令
@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @Input() highlightColor: string;
  
  constructor(private el: ElementRef) {}
  
  @HostListener('mouseenter')
  onMouseEnter() {
    this.highlight(this.highlightColor || 'yellow');
  }
}

2. 前端构建工具

2.1 Webpack 配置

// webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[contenthash].js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ],
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  },
  devServer: {
    contentBase: './dist',
    hot: true
  }
};

2.2 Babel 配置

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', {
      targets: {
        browsers: ['> 1%', 'last 2 versions']
      },
      useBuiltIns: 'usage',
      corejs: 3
    }],
    '@babel/preset-react'
  ],
  plugins: [
    '@babel/plugin-proposal-class-properties',
    '@babel/plugin-transform-runtime'
  ]
};

2.3 NPM/Yarn 包管理

// package.json
{
  "name": "my-project",
  "version": "1.0.0",
  "scripts": {
    "start": "webpack serve --mode development",
    "build": "webpack --mode production",
    "test": "jest",
    "lint": "eslint src/**/*.js"
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "webpack": "^5.50.0",
    "webpack-cli": "^4.8.0"
  }
}
# NPM 命令
npm install           # 安装依赖
npm install package   # 安装特定包
npm run start        # 运行脚本
npm update           # 更新依赖

# Yarn 命令
yarn                 # 安装依赖
yarn add package     # 安装特定包
yarn start           # 运行脚本
yarn upgrade         # 更新依赖

3. 开发工具配置

3.1 ESLint 配置

// .eslintrc.js
module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended'
  ],
  parserOptions: {
    ecmaVersion: 12,
    sourceType: 'module'
  },
  rules: {
    'no-console': 'warn',
    'react/prop-types': 'off'
  }
};

3.2 开发环境配置

// 开发服务器配置
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true
      }
    },
    historyApiFallback: true,
    hot: true
  }
};

4. 最佳实践

4.1 项目结构

my-project/
├── src/
│   ├── components/
│   ├── pages/
│   ├── services/
│   ├── utils/
│   ├── styles/
│   └── index.js
├── public/
├── tests/
├── webpack.config.js
├── babel.config.js
├── package.json
└── README.md

4.2 性能优化

  1. 代码分割
  2. 懒加载组件
  3. 缓存优化
  4. 压缩资源
  5. Tree Shaking

4.3 开发流程

  1. 使用版本控制
  2. 编写单元测试
  3. 持续集成
  4. 代码审查
  5. 文档维护

5. 调试和测试

5.1 调试工具

  1. Chrome DevTools
  2. React Developer Tools
  3. Vue DevTools
  4. Redux DevTools

5.2 测试框架

// Jest 测试示例
describe('Component tests', () => {
  it('should render correctly', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper).toMatchSnapshot();
  });
  
  it('should handle click events', () => {
    const onClick = jest.fn();
    const wrapper = mount(<Button onClick={onClick} />);
    wrapper.simulate('click');
    expect(onClick).toHaveBeenCalled();
  });
});

这份文档涵盖了主要的前端框架和工具,建议根据项目需求选择合适的技术栈,并在实践中不断深化理解。持续关注技术更新和最佳实践是提高开发效率的关键。

苏ICP备2025153828号