React - Webpack 项目脚手架搭建

把手还是伸向了前端,抽空折腾了几天,算是理清了起步门槛。

一、首先确保安装了 npm,如果没装…那就想办法装上
$ npm
Usage: npm <command>

where <command> is one of:
    access, adduser, bin, bugs, c, cache, completion, config,
    ddp, dedupe, deprecate, dist-tag, docs, doctor, edit,
    explore, get, help, help-search, i, init, install,
    install-test, it, link, list, ln, login, logout, ls,
    outdated, owner, pack, ping, prefix, profile, prune,
    publish, rb, rebuild, repo, restart, root, run, run-script,
    s, se, search, set, shrinkwrap, star, stars, start, stop, t,
    team, test, token, tst, un, uninstall, unpublish, unstar,
    up, update, v, version, view, whoami

npm <command> -h     quick help on <command>
npm -l           display full usage info
npm help <term>  search for help on <term>
npm help npm     involved overview

Specify configs in the ini-formatted file:
    /Users/xiaoyu/.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config

npm@5.6.0 /usr/local/lib/node_modules/npm
二、安装 create-react-app。如果用 WebStorm,可以跳过这一步。

IDE 可以选择创建 React App,省去了手动执行,所以创建后的目录内容是一样的。

// -g : global
$ npm install create-react-app -g
/usr/local/bin/create-react-app -> /usr/local/lib/node_modules/create-react-app/index.js
+ create-react-app@3.2.0
added 91 packages in 24.685s

$ create-react-app
Please specify the project directory:
  create-react-app <project-directory>

For example:
  create-react-app my-react-app

Run create-react-app --help to see all options.

如介绍所言,创建一个app,名字任意,合法即可

$ create-react-app my-react-app

项目结构如下:

$ ls my-react-app
README.md		    package-lock.json	public
node_modules		package.json		src
  • README.md : 你懂的
  • node_moudles : 依赖都在找个目录下
  • package.json : npm的配置文件,或者说是项目的配置文件
  • package-lock.json : 锁定版本号
  • public : 存放静态资源
  • src : 代码/资源
三、安装 webpack 全家桶

npm install 参数说明:package.json 有几个依赖节点,dependenciesdevDependenciesoptionalDependencies,前者会随着项目发布出去;后者顾名思义,只在开发时使用;后后者为可选阶段


-S, --save :依赖添加到 dependencies 节点,
-D,–save-dev :依赖添加到 devDependencies 节点
-O,–save-optional :依赖添加到 optionalDependencies 节点

以下命令,在项目根目录下执行

// 也可以放在一行执行
$ npm install webpack -D
$ npm install webpack-cli -D
$ npm install webpack-dev-server -D

注意,这里有个坑:这三个依赖的版本号一定要相互匹配,如果你要指定版本,一定要确认指定的版本号是行不通的,不然就会报错。都用最新版,目前一切正常。

四、配置 webpack server

鉴于 webpack 可用于本地 server,也可用于打包,各自使用不同的配置文件。在项目根目录创建个文件夹 wepack,用于存放 webpack 配置文件。

  1. webpack/webpack.config.js,用于开发 server
const path = require('path');
const webpack = require('webpack');
const __repo = path.dirname(__dirname);
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: { // 程序唯一入口
        'index': path.resolve(__repo, 'src/index.jsx'),
    },
    mode: 'development',
    output: { // 打包文件输出位置
        path: path.resolve(__repo, "build"),
        filename: "bundle.js",
        publicPath: "/"
    },
    devServer: {
        contentBase: [path.join(__repo, 'public'),], // 本地服务器索价在的页面所在目录
        compress: false,
        port: 7788, // server 使用端口
        disableHostCheck: true,
        inline: true, // 实时刷新
        historyApiFallback: true, // 不跳转
        hot: true
    },
    module: {
        rules: [
            {
                test: /(\.jsx|\.js)$/, // 匹配所护理文件的扩展名正则表达式
                exclude: /(node_modules|bower_components)/, // 手动添加/屏蔽的文件
                use: {
                    loader: 'babel-loader', // loader名称
                }
            },
            {
                test: /\.(css|styl)$/,
                use: [
                    {
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader'
                    }
                 ]
            },
            {
                test: /\.html$/,
                use: [
                    {loader: 'html-loader'}
                ]
            },
            {
                test: /\.(gif|jpg|png|svg|ttf|eot|woff|woff2)$/,
                use : {
                    loader: 'file-loader?name=fonts/[name].[ext]'
                }
            },
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'public/index.html'
        })
    ]
};

其中的 module,就是 webpack 的 loader,都是用来打包用的:

  • babel-loader:打包jsx、js文件,转化成浏览器认识的格式,因该loader配置选项较多,一般单抽取出独立的文件.bebelrc,放在项目根目录,webpack可以自动识别到
  • css-loaderstyle-loader:打包css、style文件
  • html-loader:打包html文件
  • file-loader:打包其他格式文件,如配置中所写

.babelrc 内容如下:

{
  "presets": ["@babel/preset-react", "@babel/preset-env"], // 支持的编码
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

其中,所有的loader、plugin,都需要手动安装

$ npm install -D babel-core babel-loader css-loader style-loader html-loader file-loader

$ npm install -D @babel/preset-env @babel/preset-react @babel/plugin-transform-runtime html-webpack-plugin
  1. 配置 package.json,使用webpack/webpack.config.js。修改 package.json 中的scripts 节点,如下:
"dev": "webpack-dev-server --config webpack/webpack.config.js"

此时,在项目根目录下执行该命令,即可。

$ npm run dev
五、配置 webpack 打包配置

和 server 类似,这里直接贴上配置文件

  1. webpack/webpack.config.build.js
const path = require('path');
const webpack = require('webpack');
const __repo = path.dirname(__dirname);
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    mode: "production",
    entry: path.resolve(__repo, 'src/index.jsx'),
    devtool: "#source-map",
    output: {
        path: path.resolve(__repo, "dist"),
        filename: "app/[name].bundle.js",
        publicPath: "/"
    },
    module: {
        rules: [
            {
                test: /(\.jsx|\.js)$/, // 匹配所护理文件的扩展名正则表达式
                exclude: /(node_modules|bower_components)/, // 手动添加/屏蔽的文件
                use: {
                    loader: 'babel-loader', // loader名称
                }
            },
            {
                test: /\.(css|styl)$/,
                use: [
                    {
                        loader: 'style-loader'
                    },
                    {
                        loader: 'css-loader'
                    }
                ]
            },
            {
                test: /\.html$/,
                use: [
                    {loader: 'html-loader'}
                ]
            },
            {
                test: /\.(gif|jpg|png|svg|ttf|eot|woff|woff2)$/,
                use : {
                    loader: 'file-loader?name=fonts/[name].[ext]'
                }
            },
        ]
    },

    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'public/index.html'
        })
    ]
};
  1. 修改package.json中的scripts节点,如下
"build": "webpack --config webpack/webpack.config.build.js"

执行打包命令后,所有文件会输出到项目根目录下的dist中。

$ npm run build

打包后的文件,配合nginx就可以访问请求了。

(完)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
npx create-react-app和使用Vite创建React应用都是常见的前端工具,它们各有优缺点。 优点: npx create-react-app: - 简单易用:create-react-app是React官方提供的脚手架工具,使用简单,适合快速搭建React项目。 - 完善的生态系统:create-react-app集成了许多常用的工具和配置,如Babel、Webpack等,使得开发者无需手动配置即可进行开发。 - 社区支持:由于create-react-app广泛使用,因此有丰富的社区支持和文档资料可供参考。 Vite: - 极速开发:Vite使用ES模块的开发服务器和即时编译机制,启动速度快,冷启动时间短,能够提供更快的开发体验。 - 原生ES模块支持:Vite利用浏览器的原生ES模块支持,无需打包和转换,能够直接在浏览器中运行和调试代码,提高开发效率。 - 插件生态系统:Vite支持丰富的插件系统,可以轻松集成各种功能和工具,如TypeScript、CSS预处理器等。 缺点: npx create-react-app: - 一体化配置:create-react-app的配置相对固定,对于一些高度定制化的需求可能不够灵活,需要手动eject来获得更多配置项的控制权。 - 较大的初始包体积:create-react-app默认集成了许多工具和库,导致初始包体积较大,对于需要快速加载的项目可能不太合适。 Vite: - 生态系统相对较新:相比create-react-app,Vite的生态系统相对较新,可能在某些功能或插件的支持上不如create-react-app成熟。 - 配置复杂性:Vite相对于传统的打包工具(如Webpack)来说,配置相对简单,但对于不熟悉ES模块化和Vite特有的配置项的开发者来说,上手可能需要一些时间。 综上所述,npx create-react-app适合快速搭建React项目,并且拥有完善的生态系统和社区支持。Vite适合追求极速开发体验、原生ES模块支持和插件生态系统的开发者。选择使用哪种工具取决于项目需求、开发经验和个人偏好。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值