美文网首页React
搭建基于 webpack2 的 react 脚手架

搭建基于 webpack2 的 react 脚手架

作者: 柏丘君 | 来源:发表于2017-05-05 18:15 被阅读4795次
    • 脚手架现已发布到 NPM,欢迎大家踊跃下载,多提意见。

    最近公司的后台管理项目,技术选型的时候决定采用 react 技术栈。在开发之前就想要一个脚手架,在热门的脚手架中,create-react-app 的热替换不太好用,而 react-starter-kit 又太复杂,下载下来后发现完全看不懂……于是干脆自己搭建一个,在搭建此脚手架的过程中,也踩了不少坑,特地分享给大家,希望一起学习。
    本文不会从零开始讲解 webpack 的知识,如果你对 webpack 还不甚了解,可以先了解相关知识再来查看本文。

    特性

    此脚手架有如下一些特性:

    • react
    • redux
    • react-redux
    • react-router
    • redux-thunk
    • hmr
    • fetch
    • es6
    • css modules
    • scss
    • postcss

    安装

    1. npm install build-react-app -g
    2. build-react-app <directory>
    3. cd <directory>
    4. npm install
    

    用法

    1. npm run dev    代码热替换模式
    2. npm run build    生产环境构建
    3. npm run serve    在服务器环境运行构建后的代码
    

    目录结构

    │  .babelrc             —— babel 配置文件
    │  .npmignore          
    │  index.html           —— 入口页面
    │  package.json
    │  webpack.config.js    —— webpack 的入口文件
    │
    ├─config                —— webpack 的主要配置放在此目录
    │      config.js        —— 常用配置文件,如端口等
    │      webpack.base.js  —— 基础配置文件
    │      webpack.dev.js   —— 开发环境配置
    │      webpack.prod.js  —— 生产环境配置
    │
    ├─src                   —— 项目源文件
    │  │  index.html
    │  │  main.js
    │  │
    │  ├─actions            —— 存放所有的 action
    │  │  │  index.js
    │  │  │
    │  │  └─allActions
    │  │          counterAction.js
    │  │
    │  ├─components         —— 组件文件夹
    │  │  │  App.js
    │  │  │
    │  │  ├─Counter
    │  │  │      Counter.js
    │  │  │      index.js
    │  │  │
    │  │  └─Welcome
    │  │          index.js
    │  │          style.scss
    │  │
    │  ├─reducer            —— 存放所有的 reducer
    │  │  │  index.js
    │  │  │  reducers.js
    │  │  │
    │  │  └─allReducers
    │  │          counter-reducer.js
    │  │
    │  ├─router             —— 存放路由
    │  │      components.js
    │  │      index.js
    │  │
    │  └─store              —— 存放 store
    │          index.js
    │
    └─static                —— 静态资源文件
            common.scss
            normalize.scss
    

    上面是脚手架生成的目录树,除了 config 目录,都是与 react 相关的,不了解 react 也没关系,我们主要讲的是 webpack 这一块,也就是 config 目录中的三个文件。

    思路

    由于配置的脚手架功能较多,因此采取将配置文件分离的策略,便于后期的维护和扩展。因此我们将文件分为:

    • 主入口文件
    • 基础配置文件
    • 开发环境配置文件
    • 生产环境配置文件
    • 通用配置文件

    下面依次进行讲解。

    如何区分开发环境和生产环境

    我们可以采用定义 Node 运行时环境变量的方法进行区分。在 package.json 定义如下命令:

      "scripts": {
        "dev": "set NODE_ENV=dev && webpack-dev-server --profile",
        "build": "rimraf dist && set NODE_ENV=prod && webpack",
        "serve": "http-server ./dist -p 8888 -o"
      }
    

    其中 set NODE_ENV=xxx 就是设置相应的环境变量,以区分生产和开发环境。在开发环境设置为 dev,生产环境设置为 prod。
    说说其他几个命令:

    rimraf dist                    // 在 build 时先移除旧有的 dist 文件夹,此命令不是必须的
    http-server ./dist -p 8888 -o  // 查看构建后的项目,-o 表示打开浏览器
    

    以上两个包都需要自行进行安装:

    npm install rimraf http-server --save-dev
    

    wbpack.config.js

    运行 webpack 时,其默认的配置文件就是 webpack.config.js,在此脚手架中,它只是一个入口文件,根据环境变量来引入相应的配置文件。
    下面是 webpack.config.js 的代码:

    // 获取 NODE 运行时的环境变量
    const env = process.env.NODE_ENV.replace(/(\s*$)|(^\s*)/ig,"");
    // 根据环境变量引入相应的配置文件
    const config = require(`./config/webpack.${env}.js`)(env);
    // 导出此模块
    module.exports = config;
    

    上面的 config 是一个函数调用的结果,也就是说 webpack.dev.js 和 webpack.prod.js 两个暴露出的是函数而不是对象,这样做的原因是方便对配置文件进行 merge。

    webpack.base.js

    这是基础的配置文件,包括了最基础的功能。
    下面是 webpack.base.js 的代码:

    const path = require("path")
    const webpack = require("webpack")
    // 导入配置文件
    const config = require("./config");
    const publicPath = config.publicPath;
    
    module.exports = function(env){
        return{
            // 入口文件:src目录下的 main.js
            entry:{
                main:path.resolve(__dirname,"../src/main.js"),
            },
            // 输出配置
            output: {
                // 输出路径:dist 目录
                path:path.resolve(__dirname,"../dist"),
                // sourceMap 名称
                sourceMapFilename: "[name].map",
                // 根据环境变量确定输出文件的名称
                // 如是生产环境,则文件名中带有一个长度为 16 的 hash 值
                filename:(env === "dev")?"[name].js":"[name].[hash:16].js",
                publicPath,
            },
            resolve: {
                extensions: [".ts", ".js", ".json"],
                modules: [path.join(__dirname, "../src"), "node_modules"]
            },
            module:{
                loaders:[
                    {
                        test:/\.jsx?$/,
                        use:["babel-loader"],
                        exclude:"/node_modules/"
                    },
                    { 
                        test: /\.(png|jpg|gif)$/, 
                        use: ["url-loader?limit=20000&name=images/[hash:16].[ext]"], 
                        exclude: "/node_modules/" 
                    },
                    // 个人比较偏爱 scss,因此采用 scss 作为样式文件
                    { 
                        test: /\.scss$/, 
                        // sass-loader:处理 .scss 后缀的文件
                        // postcss-loader:对样式文件自动化处理,如自动添加前缀
                        // css-loader?modules:将 scss 文件转换成 css 文件,并开启模块化
                        use: ["style-loader","css-loader?modules","postcss-loader","sass-loader"], 
                        // 我们只想模块化 src 中的 scss 文件,并不想对所有的样式文件进行模块化
                        exclude: ["/node_modules/",path.resolve(__dirname,"../static")]
                    },
                    { 
                        test: /\.scss$/, 
                        // 对 static 目录中的 scss 文件进行处理,我们不想此文件中的样式文件被模块化
                        use: ["style-loader","css-loader","postcss-loader","sass-loader"], 
                        // 该处理只包含 static 目录中的文件
                        include: [path.resolve(__dirname,"../static")]
                    },
                ],
            },
        }
    }
    

    由于项目中可能存在两种样式文件:组件本身的样式和外部的样式文件(或公共样式文件),我们在进行 CSS 模块化的时候,可以选择只模块化 src 目录中的文件,而 static 目录中的文件不进行模块化,用来存放一些公共的样式。因此上面对 scss 文件进行了两次处理的原因就在这里。

    webpack.dev.js

    此文件用来存放开发环境的配置文件。
    下面是 webpack.dev.js 的代码:

    const path = require("path");
    const webpack = require("webpack")
    // 此插件用来合并 webpack 配置
    const webpackMerge = require("webpack-merge");
    // 打开浏览器插件
    const OpenBrowserPlugin = require("open-browser-webpack-plugin");
    // postcss 的自动补全插件
    const autoprefixer = require("autoprefixer");
    const precss = require("precss");
    
    // 引入基础配置文件
    const baseConfig = require("./webpack.base.js");
    const config = require("./config");
    const port = config.port;
    
    module.exports = function(env){
        console.log(`
    #################################################
      Server is listening at: http://localhost:${config.port} 
    #################################################
        `);
        // 合并文件
        return webpackMerge(baseConfig(env),{
            entry:[
                "react-hot-loader/patch",
                "webpack-dev-server/client?http://localhost:" + port,
                "webpack/hot/only-dev-server",
                path.resolve(__dirname,"../src/main.js"),
            ],
            devtool: "cheap-module-source-map",
            plugins:[
                // 开启热替换
                new webpack.HotModuleReplacementPlugin(),
                // 编译完成后自动打开浏览器
                new OpenBrowserPlugin({ url: "http://localhost:" + port }),
                // 配置 postcss 
                new webpack.LoaderOptionsPlugin({
                    options:{
                        postcss(){
                            return[precss, autoprefixer];
                        }
                    }
                })
            ],
            // 配置 webpack-dev-server
            devServer:{
                hot:true,
                port:config.port,
                historyApiFallback:true,
            }
        })
    }
    

    webpack-merge 插件用来合并 webpack 的配置,我们这里将 webpack.base.js 和新定义的配置进行合并。

    webpack.prod.js

    此文件用来存放生产环境的配置文件。
    下面是 webpack.prod.js 的代码:

    const path = require("path");
    const webpack = require("webpack");
    const webpackMerge = require("webpack-merge");
    // 抽取公共代码
    const ExtractTextPlugin = require("extract-text-webpack-plugin"); 
    // HTML 模板插件
    const HTMLWebpackPlugin = require("html-webpack-plugin");
    const autoprefixer = require("autoprefixer");
    const precss = require("precss");
    const baseConfig = require("./webpack.base.js");
    const config = require("./config.js");
    // 项目中用到的第三方库
    const vendor = config.vendor;
    
    module.exports = function(env){
        return webpackMerge(baseConfig(env),{
            entry:{
                main:path.resolve(__dirname,"../src/main.js"),
                vendor,
            },
            module:{
                rules:[
                    {
                        test:/\.jsx?$/,
                        use:["babel-loader"],
                        exclude:"/node_modules/"
                    },
                    { 
                        test: /\.(png|jpg|gif)$/, 
                        use: ["url-loader?limit=20000&name=images/[hash:16].[ext]"], 
                        exclude: "/node_modules/" 
                    },
                    // 抽取 css 文件,使用 extract-text-webpack-plugin 插件完成
                    // 配置方式和 webpack.base.js 中相似,即在抽取过程中只对 src 中的样式文件进行模块化
                    { 
                        test: /\.s?css$/, 
                        use: ExtractTextPlugin.extract({
                                fallback: "style-loader",
                                use: [
                                    "css-loader?minimize&modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]",
                                    "sass-loader",
                                    "postcss-loader"
                                ]
                             }),
                        exclude: ["/node_modules/",path.resolve(__dirname,"../static")]
                    },
                    { 
                        test: /\.s?css$/, 
                        use: ExtractTextPlugin.extract({
                                fallback: "style-loader",
                                use: [
                                    "css-loader?minimize",
                                    "sass-loader",
                                    "postcss-loader"
                                ]
                             }),
                        include: [path.resolve(__dirname,"../static")]
                    }
                ],
            },
            plugins:[
                // 压缩 js,以及一些选项
                new webpack.optimize.UglifyJsPlugin({
                    compress: {
                        warnings: false,
                        screw_ie8: true,
                        conditionals: true,
                        unused: true,
                        comparisons: true,
                        sequences: true,
                        dead_code: true,
                        evaluate: true,
                        if_return: true,
                        join_vars: true,
                    },
                    output: {
                        comments: false,
                    },
                }),
                // 定义抽取出的 css 的文件名
                new ExtractTextPlugin({
                    filename:"style.[contenthash:16].css",
                    disable:false,
                    allChunks:true,
                }),
                // 自动生成 HTML 文件,需要指定一个模板
                new HTMLWebpackPlugin({
                    template:"src/index.html" 
                }),
                // 抽取公共的库
                new webpack.optimize.CommonsChunkPlugin({
                    name: ["vendor","manifest"]
                }),
                // 定义环境变量
                // 在打包 react 时会根据此环境变量进行优化
                new webpack.DefinePlugin({
                    "process.env": { 
                        NODE_ENV: JSON.stringify("production") 
                    }
                }),
                new webpack.LoaderOptionsPlugin({
                    options:{
                        postcss(){
                            return[precss, autoprefixer];
                        },
                        sassLoader: {
                            sourceMap: true
                        },
                    }
                })
            ]
        })
    }
    

    config.js

    此文件主要用来存放公共的配置,如公共的第三方库,端口,publicPath 等,方便管理。
    以下是该文件的代码:

    module.exports = {
        port:8080,
        vendor:[
            "react",
            "react-dom",
            "react-hot-loader",
            "react-router",
            "redux",
            "react-redux",
            "prop-types",
            "isomorphic-fetch",
            "es6-promise",
            "redux-thunk",
            "classnames",
        ],
        publicPath:"/",
    }
    

    总结

    当你学会自己搭建脚手架,了解了脚手架的基本套路后,就可以定制各种各样的配置了,根据自己的需求随意搭配。再也不用在开发前为选用脚手架而烦恼了,自己搭过一次后,即使采用别人的脚手架,在出现问题后也可以从容解决。

    参考资料

    完。

    相关文章

      网友评论

      • YichenCWG:安装包能够下载,但是使用build-react-app <directory>命令新建自己的项目 生成的是一个空的文件夹了,请问是什么问题呢
      • 笨笨小香蕉:大神,mac环境安装这个脚手架报错。
        env: node\r: No such file or directory
        怎么搞》?
        柏丘君: @笨笨小香蕉 您直接将配置文件复制下来吧,我是在windows下搭建的,mac没有试过哦
      • freeMan_d5ca:大神,我用了你的脚手架,发现你只有sass的loader,如果换成css就会报错,如果加上cssloader,怎么在webpack里配置啊,谢谢大神。
        柏丘君:如果您删掉所有关于 sass 的配置还是报错的话,可以仍然使用 .scss 后缀名,然后在 .scss 中继续使用 css 就行了,这是个比较简单的解决办法,sass 是兼容 css 的
        柏丘君:另外,当初配这个脚手架是因为 create-react-app 这个官方脚手架对于热更新支持不好,于是选择自行配置,配置的肯定没有官方好。事实上,对 create-react-app 做一些简单的修改就可以使其支持热更新了,博客里面有一篇文章,您可以去看看。置于这个脚手架,主要是学习使用,现在用得少了,都用官方的脚手架。
        柏丘君:如果不使用 scss 只使用 css 的话,把配置文件中所有关于 sass 的东西删掉试试
      • Yunfly:mark!

      本文标题:搭建基于 webpack2 的 react 脚手架

      本文链接:https://www.haomeiwen.com/subject/bzrstxtx.html