react项目框架搭建

  1. 解决下包太慢问题:npm切换成国内的镜像服务来使用,淘宝镜像:

    npm config set registry http://registry.npm.taobao.org/

配置项目

  1. 初始化 package.json

    npm init -y
    
  2. 安装依赖

    npm install react react-dom
    npm install -D webpack webpack-cli webpack-dev-server html-webpack-plugin
    npm install -D typescript ts-loader
    npm install -D less less-loader css-loader style-loader
    
  3. 创建 TypeScript 配置文件 tsconfig.json

    {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "jsx": "react",
        "strict": false,
        "esModuleInterop": true
      },
      "include": ["src/**/*.tsx", "src/**/*.ts"],
      "exclude": [
        "node_modules",
        "build",
        "scripts",
        "webpack"
      ]
    }
    
  4. 创建 Webpack 配置文件 webpack.config.js

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
        entry: './src/index.tsx',
        output: {
            path: path.resolve(__dirname, 'dist'),
            filename: 'bundle.js',
        },
        module: {
            rules: [
                {
                    test: /\.(ts|tsx)$/,
                    exclude: /node_modules/,
                    use: 'ts-loader',
                },
                {
                    test: /\.less$/,
                    use: [
                        'style-loader',
                        {
                            loader: 'css-loader',
                            options: {
                                modules: true,
                            }
                        }
                        , 'less-loader'],
                },
            ],
        },
        resolve: {
            extensions: ['.tsx', '.ts', '.js'],
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: './public/index.html',
            }),
        ],
        devServer: {
            static: {
                directory: path.join(__dirname, 'dist'),
            },
            port: 3010,
            historyApiFallback: true,
            open: true,
        },
    };
    
    
  5. 创建项目文件结构

    react-webpack-ts-less/
    ├── src/
    │   ├── components/
    │   │   └── App.tsx
    │   └── index.tsx
    ├── public/
    │   └── index.html
    ├── package.json
    ├── tsconfig.json
    └── webpack.config.js
    
    
  6. 配置package.json启动

    "scripts": {
      "start": "webpack serve --mode development",
      "build": "webpack --mode production",
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐