Webpack+React项目搭建

Webpack 是一个使用比较广泛的前端项目打包工具,可以帮我们处理一些诸如 typescript、es6+、Vue、tsx 之类浏览器无法直接支持的问题,将项目打包成各个浏览器都可以直接支持的 js 文件。类似的工具还有 Vite 等。

参考资料

概念

  • entry: 使用哪个模块来作为构建的起始入口。
  • output: 最终打包后的文件放在哪里,以及如何命名这些文件。
  • loader: 是处理文件的转换器,用于对模块源码进行转换,webpack 只能识别 js、json 文件,像 css 、ts 、jsx等文件都需要通过 loader 进行转换。
  • plugin: 是一种可扩展的机制,可以打包过程中添加额外的功能。比如打包优化,资源管理,注入环境变量等。
  • mode: 对于不同的环境,我们往往需要不同的配置,通过设置 mode 参数来选择环境。

项目初始化

略过 node.js 安装之类的前置步骤。

// 创建项目文件夹
mkdir start-react
// 初始化
npm init

typescript及React配置

引入 typescript及React

// react
npm add -D react react-dom
npm add -D @types/react @types/react-dom

// typescript
npm add -D typescript

// 初始化 typesript 配置,生成 tsconfig.js 文件
tsc --init

tsconfig.js 文件配置:

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "ESNEXT",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "ESNext",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    "noEmit": true,                        /* Do not emit outputs. */
    "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    "noUnusedLocals": true,                /* Report errors on unused locals. */
    "noUnusedParameters": true,            /* Report errors on unused parameters. */
    "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    "paths": {
      "common/*": [
        "src/common/*"
      ],
      "@/*": [
        "src/*"
      ]
    },                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  },
  "include": ["src"]
}

创建 src 目录,在该目录下创建文件 App.tsx 及 index.tsx,文件内容如下:

// App.tsx
import * as React from 'react'

const App: React.FC = () => {
    return (
        <div>
            <h1>Hello lozhu!</h1>
        </div>
    )
}

export default App
import * as React from 'react'
import * as ReactDOM from 'react-dom/client'

import App from './App'

const root = ReactDOM.createRoot(document.getElementById('app')!)
root.render(<App />)

webpack配置

引入 webpack

npm add -D webpack webpack-cli webpack-dev-server webpack-merge

开发、生产环境配置

引入 cross-env

npm add -D cross-env

创建 scripts 文件夹及 webpack.base.js、webpack.dev.js、webpack.prod.js 文件

// webpack.base.js
const path = require('path')

module.exports = {
    entry: path.resolve(__dirname, '../src/index.tsx'),
    output: {
        path: path.resolve(__dirname, '../dist'),  // 打包后的文件存放地址
        filename: '[name].[hash:8].js'  // 打包的文件名
    }
}
// webpack.dev.js
const { merge } = require('webpack-merge')
const base = require('./webpack.base.js')

module.exports = merge(base, {
    mode: 'development',
    devServer: {
        open: true,  // 编译完自动打开浏览器
        port: 8080
    }
})
// webpack.prod.js
const { merge } = require('webpack-merge')
const base = require('./webpack.base.js')

module.exports = merge(base, {
    mode: 'production'  // 生产模式
})

修改启动脚本

修改 package.json

{
  "name": "start-react",
  "version": "1.0.0",
  "description": "no description",
  "main": "index.js",
  "scripts": {
    // 启动开发环境
    "dev": "cross-env NODE_ENV=development webpack serve -c scripts/webpack.dev.js",
    // 生产打包
    "build": "cross-env NODE_ENV=production webpack -c scripts/webpack.prod.js"
  },
  ...
} 

Babel配置

Babel 是一个 JavaScript 编译器。主要用于将高版本的JavaScript代码转为向后兼容的JS代码,从而能让我们的代码运行在更低版本的浏览器或者其他的环境中。

由于 webpack 只能识别js、json 文件, 无法识别 jsx/tsx 文件,此时如果我们尝试启动项目肯定会报错。如何让 webpack 能识别呢?此时我们就需要使用babel-loader 来转换代码,babel-loader 可以让 webpack 在构建的时候借助 Babel 对JS代码进行转译。

引入依赖

npm add -D babel-loader @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript

修改 webpack.base.js 配置

const path = require('path')

module.exports = {
    entry: path.resolve(__dirname, '../src/index.tsx'),
    output: {
        path: path.resolve(__dirname, '../dist'),  // 打包后的文件存放地址
        filename: '[name].[hash:8].js'  // 打包的文件名
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.mjs', '.js', '.json', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, '../')
        }
    },
    module: {
        rules: [
            {
                test: /.(jsx?)|(tsx?)$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['@babel/preset-env'],
                            ['@babel/preset-typescript'],
                            ['@babel/preset-react']
                        ]
                    }
                }
            }
        ]
    }
}

运行打包命令

npm run build

打包完成后,会生成 dist 目录,但是还需要 index.html 文件才能访问。

HtmlWebpackPlugin配置

可以使用 HtmlWebpackPlugin 在每次打包时自动生成 index.html 入口文件。

npm add -D html-webpack-plugin

修改 webpack.base.js 文件内容

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: path.resolve(__dirname, '../src/index.tsx'),
    output: {
        path: path.resolve(__dirname, '../dist'),  // 打包后的文件存放地址
        filename: '[name].[hash:8].js'  // 打包的文件名
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.mjs', '.js', '.json', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, '../')
        }
    },
    module: {
        rules: [
            {
                test: /.(jsx?)|(tsx?)$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['@babel/preset-env'],
                            ['@babel/preset-typescript'],
                            ['@babel/preset-react']
                        ]
                    }
                }
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, '../src/index.html')  // 使用自定义模板
        })
    ]
}

在 src 目录下创建 index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hello webpack</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>

再次运行打包命令后,dist 目录下产生了 index.html 文件,浏览器打开就能看到 App.tsx 中定义的内容。

各种loader配置

图片加载

引入依赖 url-loader 及 file-loader

npm add -D file-loader url-loader

在根目录下创建图片文件夹 assets/images,引入图片 img1.jpg 和 img2.jpg

在 App.tsx 中引入图片

import * as React from 'react'
import img1 from '../assets/images/img1.jpg'

const App: React.FC = () => {
    return (
        <div>
            <h1>Hello lozhu!</h1>
            <div>
                <img src={img1} />
            </div>
        </div>
    )
}

export default App

修改 webpack.base.js 配置

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: path.resolve(__dirname, '../src/index.tsx'),
    output: {
        path: path.resolve(__dirname, '../dist'),  // 打包后的文件存放地址
        filename: '[name].[hash:8].js'  // 打包的文件名
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.mjs', '.js', '.json', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, '../')
        }
    },
    module: {
        rules: [
            {
                test: /.(jsx?)|(tsx?)$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['@babel/preset-env'],
                            ['@babel/preset-typescript'],
                            ['@babel/preset-react']
                        ]
                    }
                }
            },
            {
                test: /\.(jpg|png)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 2000
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, '../src/index.html')  // 使用自定义模板
        })
    ]
}

重新打包即可看到图片加载出来了:eyes:

css样式

css-loader 只能帮我们将 css 解析成 js,但不能挂载到元素上。style-loader 可以帮我们实现将样式挂载到元素上,它负责将 css 样式通过 style 标签插入到 DOM 中。通过 style-loader 实现样式挂载,自动添加 style 标签到 head 中。

使用 postcss 处理 css

npm add -D style-loader css-loader postcss postcss-loader postcss-preset-env

新建 src/assets/style/mystyle.css 样式文件

// mystyle.css
/* 标准图片样式 */
.standard-img {
    width: 100px;
    height: 60px;
    border-radius: 8px;
}

修改 App.tsx 文件引入 css

import * as React from 'react'
import img1 from './src/assets/images/img1.jpg'
import './assets/style/mystyle.css'

const App: React.FC = () => {
    return (
        <div>
            <h1>Hello lozhu!</h1>
            <div>
                <img src={img1} className="standard-img" />
            </div>
        </div>
    )
}

export default App

修改 webpack.base.js 文件

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: path.resolve(__dirname, '../src/index.tsx'),
    output: {
        path: path.resolve(__dirname, '../dist'),  // 打包后的文件存放地址
        filename: '[name].[hash:8].js'  // 打包的文件名
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.mjs', '.js', '.json', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, '../')
        }
    },
    module: {
        rules: [
            {
                test: /.(jsx?)|(tsx?)$/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['@babel/preset-env'],
                            ['@babel/preset-typescript'],
                            ['@babel/preset-react']
                        ]
                    }
                }
            },
            {
                test: /\.(jpg|png)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 2000
                        }
                    }
                ]
            },
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                    {
                        loader: 'postcss-loader',
                        options: {		
                            postcssOptions: {
                                plugins: [['postcss-preset-env', {}]]
                            }
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, '../src/index.html')  // 使用自定义模板
        })
    ]
}

重新打包之后可以看到图片的大小变为想要的样式了。