新建一个 React TypeScript 项目,并使用 Webpack 进行构建和打包

要用 create-react-app 新建一个 React TypeScript 项目,并使用 Webpack 进行构建和打包,可以按照以下步骤进行操作:

步骤 1:使用 create-react-app 创建 React TypeScript 项目

  1. 确保你已经安装了 Node.js 和 npm(Node 包管理器)。

  2. 打开命令行工具,运行以下命令来安装 create-react-app

    npx create-react-app my-app --template typescript
    

    这里的 my-app 是你项目的名称,可以根据需要更改。

步骤 2:安装 Webpack 和相关插件

  1. 进入项目目录:

    cd my-app
    
  2. 安装 Webpack 和相关插件:

    npm install --save-dev webpack webpack-cli webpack-dev-server typescript ts-loader
    
  3. 安装一些常用的 Webpack 插件:

    npm install --save-dev html-webpack-plugin clean-webpack-plugin babel-loader @babel/preset-env @babel/preset-typescript @babel/preset-react style-loader css-loader url-loader image-webpack-loader
    

步骤 3:配置 Webpack

  1. 在项目根目录创建一个名为 webpack.config.js 的文件,并添加以下内容:

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const { CleanWebpackPlugin } = require('clean-webpack-plugin');
    
    module.exports = {
      entry: './src/index.tsx',
      output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
      },
      devtool: 'inline-source-map',
      devServer: {
        port: 8080, // you can change the port
        hot: true
      },
      resolve: {
        extensions: ['.ts', '.tsx', '.js']
      },
      module: {
        rules: [
        	{
             test: /\.(ts|js)x?$/,
             exclude: /node_modules/,
             use: {
               loader: "babel-loader",
               options: {
                 presets: [
                   "@babel/preset-env",
                   "@babel/preset-typescript",
                   "@babel/preset-react",
                 ],
               },
             },
           },
          {
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
          },
          {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']
          },
          {
             test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
             use: [
               {
                 loader: "url-loader",
                 options: {
                   limit: 10000,
                   name: "img/[name]_[hash:8].[ext]",
                 },
               },
               {
                 loader: "image-webpack-loader",
                 options: {
                   disable: true, // webpack@2.x and newer
                 },
               },
             ],
           },
        ]
      },
      plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
          template: './public/index.html'
        })
      ]
    };
    
  2. package.json 文件中添加以下脚本:

    "scripts": {
      "dev": "webpack serve --open --config webpack.config.js --mode development",
      "build": "webpack --config webpack.config.js --mode production"
    }
    

步骤 4:更新 TypeScript 配置

  1. 创建一个 tsconfig.json 文件(如果 create-react-app 已经生成了一个,你可以根据需要进行修改):

    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "es2015"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noFallthroughCasesInSwitch": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": false,
        "jsx": "react-jsx"
      },
      "include": ["src"]
    }
    

步骤 5:启动开发服务器

  1. 运行以下命令启动开发服务器:

    npm run dev
    
  2. 访问浏览器中的 http://localhost:8080,你应该能看到你的 React 应用正在运行。

步骤 6:构建项目

  1. 运行以下命令构建项目:

    npm run build
    

构建后的文件将会放在 dist 目录中,你可以将其用于部署。

通过以上步骤,你已经成功创建了一个使用 TypeScript 的 React 项目,并使用 Webpack 进行构建和打包。

  • 23
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,首先你需要安装webpack5、reacttypescript、eslint以及相关的loader和插件。你可以通过以下命令安装它们: ``` npm install webpack webpack-cli webpack-dev-server react react-dom @types/react @types/react-dom typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-config-airbnb eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks prettier -D ``` 接下来,你需要创建一个webpack配置文件,可以命名为`webpack.config.js`,在该文件中配置webpack相关内容: ```javascript 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', }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, module: { rules: [ { test: /\.(ts|tsx)$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', ], }, }, { loader: 'ts-loader', }, ], }, { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', }), ], devtool: 'inline-source-map', devServer: { contentBase: './dist', port: 3000, }, mode: 'development', }; ``` 在上面的配置中,我们指定了入口文件为`src/index.tsx`,打包后的输出文件为`dist/bundle.js`。我们还通过resolve属性指定了文件的拓展名,这样在引入文件时就不用指定拓展名了。 在module属性中,我们定义了不同类型文件的loader,例如对于`.tsx`和`.ts`文件,我们使用了`babel-loader`和`ts-loader`,对于`.js`和`.jsx`文件,我们只使用了`babel-loader`。此外,我们还使用了`style-loader`和`css-loader`处理`.css`文件。 在plugins属性中,我们使用了`HtmlWebpackPlugin`插件,用于生成HTML文件。在devServer属性中,我们指定了开发服务器的端口和从哪个文件夹提供内容。 最后,我们使用了`inline-source-map`作为开发模式下的source-map,将模式设置为`development`。 接下来,你需要创建一个`.babelrc`文件,用于配置babel: ```json { "presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"] } ``` 然后,你需要创建一个`.eslintrc.json`文件,用于配置eslint: ```json { "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "extends": ["airbnb", "plugin:@typescript-eslint/recommended", "prettier"], "rules": { "prettier/prettier": ["error"], "react/jsx-filename-extension": [1, { "extensions": [".tsx"] }], "import/extensions": ["error", "never", { "svg": "always" }] }, "settings": { "import/resolver": { "node": { "extensions": [".js", ".jsx", ".ts", ".tsx"] } } } } ``` 在上面的配置中,我们使用了`@typescript-eslint/parser`解析Typescript代码,并使用了`@typescript-eslint/eslint-plugin`插件提供的规则。我们还继承了`eslint-config-airbnb`和`eslint-config-prettier`,并使用了一些自定义的规则。 最后,你需要在`package.json`中添加一些scripts,用于启动开发服务器和打包代码: ```json { "scripts": { "start": "webpack serve --mode development", "build": "webpack --mode production" } } ``` 现在你就可以使用`npm start`命令启动开发服务器,使用`npm run build`命令打包代码了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值