React技术栈+Express+Mongodb实现个人博客 -- Part 4

内容回顾

前面的篇幅主要介绍了:

到目前阶段,你对Express, Webpack, React已经有了基本的了解,但前端页面服务和API服务目前还是分离的,本篇文章主要介绍:

  • 使用Webpack打包工程
  • 使用常用的插件

package.json

修改package.json文件,安装需要的package

{
  "name": "react_express_blog",
  "version": "1.0.0",
  "description": "react-express-mongo demo",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch-client": "cross-env NODE_ENV=development node ./server/index.js",
    "start-prod": "cross-env NODE_ENV=production node bin/server",
    "start-dev-api": "nodemon --watch server/api server/api/index.js",
    "start": "npm run watch-client & npm run start-dev-api"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/sam408130/react-blog/tree/part3"
  },
  "author": "Sam",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/sam408130/react-blog/tree/part3/issues"
  },
  "homepage": "https://github.com/sam408130/react-blog/tree/part3",
  "dependencies": {
    "antd": "^2.13.1",
    "axios": "^0.16.2",
    "bluebird": "^3.5.0",
    "body-parser": "^1.18.0",
    "compression": "^1.7.0",
    "connect-history-api-fallback": "^1.3.0",
    "cookie-parser": "^1.4.3",
    "cookies": "^0.7.1",
    "dateformat": "^3.0.2",
    "echarts-for-react": "^2.0.0",
    "express": "^4.15.4",
    "express-session": "^1.15.5",
    "http-proxy": "^1.16.2",
    "markdown": "^0.5.0",
    "mongoose": "^4.11.11",
    "qs": "^6.5.1",
    "react": "^15.6.1",
    "react-addons-pure-render-mixin": "^15.6.0",
    "react-dom": "^15.6.1",
    "react-helmet": "^5.2.0",
    "react-markdown": "^2.5.0",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "react-slick": "^0.15.4",
    "redux": "^3.7.2",
    "redux-saga": "^0.15.6",
    "remark": "^8.0.0",
    "remark-react": "^4.0.1",
    "serialize-javascript": "^1.4.0",
    "serve-favicon": "^2.4.4"
  },
  "devDependencies": {
    "autoprefixer": "^7.1.4",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-import": "^1.4.0",
    "babel-plugin-react-transform": "^2.0.2",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-remove-console": "^6.8.5",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.6.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-react-hmre": "^1.1.1",
    "babel-preset-react-optimize": "^1.0.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-register": "^6.26.0",
    "babel-runtime": "^6.26.0",
    "clean-webpack-plugin": "^0.1.16",
    "concurrently": "^3.5.0",
    "cross-env": "^5.0.5",
    "css-loader": "^0.28.7",
    "extract-text-webpack-plugin": "^3.0.0",
    "file-loader": "^0.11.2",
    "html-webpack-plugin": "^2.30.1",
    "install": "^0.10.1",
    "less": "^2.7.2",
    "less-loader": "^4.0.5",
    "node-loader": "^0.6.0",
    "node-sass": "^4.5.3",
    "nodemon": "^1.12.0",
    "npm": "^5.4.1",
    "open-browser-webpack-plugin": "0.0.5",
    "postcss-loader": "^2.0.6",
    "progress-bar-webpack-plugin": "^1.10.0",
    "react-hot-loader": "^3.0.0-beta.6",
    "redbox-react": "^1.5.0",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "url-loader": "^0.5.9",
    "webpack": "^3.5.6",
    "webpack-dev-middleware": "^1.12.0",
    "webpack-hot-middleware": "^2.19.1",
    "webpack-isomorphic-tools": "^3.0.3"
  }
}

上面的配置文件是工程所需要的所有模块,先安装,下面会逐一介绍用途:

npm install 

webpack配置文件

在根目录创建webpack开发环境的配置文件webpack.dev.js

首先看一下完整的文件内容

const pathLib = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const config = require('./config/config');

const ROOT_PATH = pathLib.resolve(__dirname);
const ENTRY_PATH = pathLib.resolve(ROOT_PATH, 'src');
const OUTPUT_PATH = pathLib.resolve(ROOT_PATH, 'build');
const AppHtml = pathLib.resolve(ENTRY_PATH,'index.html')
console.log(pathLib.resolve(ENTRY_PATH, 'index.js'));

module.exports = {
    entry: {
        index: [
          'react-hot-loader/patch',
          `webpack-hot-middleware/client?path=http://${config.host}:${config.port}/__webpack_hmr`,
          'babel-polyfill',
          pathLib.resolve(ENTRY_PATH, 'index.js')
        ],
        vendor: ['react', 'react-dom', 'react-router-dom']
    },
    output: {
        path: OUTPUT_PATH,
        publicPath: '/',
        filename: '[name]-[hash:8].js'
    },
    devtool: 'cheap-module-eval-source-map',
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {
                test: /\.css$/,
                exclude: /node_modules/,
                use: ['style-loader',
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            localIdentName: '[name]-[local]-[hash:base64:5]',
                            importLoaders: 1
                        }
                    },
                    'postcss-loader'
                ]
            },
            {
                test: /\.css$/,
                include: /node_modules/,
                use: ['style-loader',
                    {
                        loader: 'css-loader'
                    },
                    'postcss-loader'
                ]
            },
            {
                test: /\.less$/,
                use: ["style-loader", 'css-loader', "postcss-loader", "less-loader"]
            },
            {
                test: /\.(png|jpg|gif|JPG|GIF|PNG|BMP|bmp|JPEG|jpeg)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192
                        }
                    }
                ]
            },
            {
                test: /\.(eot|woff|ttf|woff2|svg)$/,
                use: 'url-loader'
            }
        ]
    },
    plugins: [
        new CleanPlugin(['build']),
        new ProgressBarPlugin(),
        new webpack.optimize.AggressiveMergingPlugin(),//改善chunk传输
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            "progress.env.NODE_ENV": JSON.stringify('development')
        }),
        new HtmlWebpackPlugin({
            inject: true,
            template: AppHtml,
        }),
        new webpack.NoEmitOnErrorsPlugin(),//保证出错时页面不阻塞,且会在编译结束后报错
        new webpack.HashedModuleIdsPlugin(),//用 HashedModuleIdsPlugin 可以轻松地实现 chunkhash 的稳定化
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            minChunks: function (module) {
                return module.context && module.context.indexOf('node_modules') !== -1;
            }
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: "manifest"
        }),
        new OpenBrowserPlugin({
            url: `http://${config.host}:${config.port}`
        })
    ],
    resolve: {
        extensions: ['.js', '.json', '.sass', '.scss', '.less', 'jsx']
    }
}

文件中的几个参数,entry, output, devtool, module, plugins起的作用,在上一篇内容都有介绍,没有完全理解的同学,可以再回看一下React技术栈+Express+Mongodb实现个人博客 -- Part 3 Express + Mongodb创建Server端webpack的介绍。

定义参数

文件头部是下面配置内容中使用的参数,统一写在头部可以方便调用

entry

index部分定义工程的入口,文件中分为4个部分:

  • react-hot-loader/patch 结合babel-polyfill, 允许我们在使用jsx语法编写react时,能让修改的部分自动刷新。但这和自动刷新网页是不同的,因为 hot-loader 并不会刷新网页,而仅仅是替换你修改的部分。
  • webpack-hot-middleware,允许Express 结合 Webpack 实现HMR。HMR 即 Hot Module Replacement 是 Webpack 一个重要的功能。它可以使我们不用通过手动地刷新浏览器页面实现将我们的更新代码实时应用到当前页面中。
  • index.js是博客的入口页面
  • vendor,该部分的作用是,将指定的模块打包成一个vendor.js文件,从最后编译的bundle.js工程文件中分离出来。
output

该部分定义打包文件输出的路径,由于我们使用了html-webpack-plugin插件,这里就可以使用文件名加hash的方法,解决缓存问题。

devtool

开发总是离不开调试,方便的调试能极大的提高开发效率,不过有时候通过打包后的文件,你是不容易找到出错了的地方,对应的你写的代码的位置的,Source Maps就是来帮我们解决这个问题的。

通过简单的配置,webpack就可以在打包时为我们生成的source maps,这为我们提供了一种对应编译文件和源文件的方法,使得编译后的代码可读性更高,也更容易调试。

在webpack的配置文件中配置source maps,需要配置devtool,它有以下四种不同的配置选项,各具优缺点,描述如下:

devtool 配置结果
source-map 在一个单独的文件中产生一个完整且功能完全的文件。这个文件具有最好的source map,但是它会减慢打包速度;
cheap-module-source-map 在一个单独的文件中生成一个不带列映射的map,不带列映射提高了打包速度,但是也使得浏览器开发者工具只能对应到具体的行,不能对应到具体的列(符号),会对调试造成不便;
eval-source-map 使用eval打包源文件模块,在同一个文件中生成干净的完整的source map。这个选项可以在不影响构建速度的前提下生成完整的sourcemap,但是对打包后输出的JS文件的执行具有性能和安全的隐患。在开发阶段这是一个非常好的选项,在生产阶段则一定不要启用这个选项
cheap-module-eval-source-map 这是在打包文件时最快的生成source map的方法,生成的Source Map 会和打包后的JavaScript文件同行显示,没有列映射,和eval-source-map选项具有相似的缺点;

这里我们使用cheap-module-eval-source-map

module

上一节我们介绍了loaders的作用,以及如何让css文件模块化。module部分是我们使用的所有loaders,在完成该部分时,记得在根路径上配置.babelrcpostcss.config.js文件

// .babelrc
{
  "presets": ["es2015","react","stage-0","env"],
  "plugins": ["react-hot-loader/babel",["import", { "libraryName": "antd", "style": true }],"transform-runtime","transform-class-properties"],
  "env": {
    "production":{
      "preset":["react-optimize"]
    }
  }
}
// postcss.config.js
module.export = {
    plugins:[
        require('autoprefixer')({browsers:'last 2 versions'})
    ]
};
plugins
1. html-webpack-plugin

这个插件的主要作用有两个:

  • 为html文件中引入的外部资源如script、link动态添加每次compile后的hash,防止引用缓存的外部文件问题
  • 可以生成创建html入口文件,比如单页面可以生成一个html文件入口,配置N个html-webpack-plugin可以生成N个页面入口

代码中是这么定义的

const AppHtml = pathLib.resolve(ENTRY_PATH,'index.html')
...
new HtmlWebpackPlugin({
     inject: true,
     template: AppHtml,
}),

AppHtml是我们定义的模板文件:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <title>Sam's Blog</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

这样配置后,打包时这个html文件会自动引用打包好的bundle.js和其他文件

2. open-browser-webpack-plugin

这个插件允许传入一个url地址,作用是当webpack打包成功后,会在浏览器中自动打开传入的地址,使用方法是:

        new OpenBrowserPlugin({
            url: `http://${config.host}:${config.port}`
        })
3. progress-bar-webpack-plugin

打包过程显示进度

屏幕快照 2017-11-02 下午6.19.18.png
4. clean-webpack-plugin

用户清除生产环境下,无效的输出文件。

5. webpack.optimize.AggressiveMergingPlugin

在工程文件中,经常会在不同文件中引用同一个module,使用该配置可以防止重复打包,减小最终文件的大小。

启动项目

我们的项目入口是服务端的server.js

import path from 'path';
import Express from 'express';
import favicon from 'serve-favicon'
import httpProxy from 'http-proxy';
import compression from 'compression';
import connectHistoryApiFallback from 'connect-history-api-fallback';
import config from '../config/config';

const app = new Express();
const port = config.port;
const targetUrl = `http://${config.apiHost}:${config.apiPort}`;
const proxy = httpProxy.createProxyServer({
    target:targetUrl
});

app.use('/api', (req,res) => {
    proxy.web(req,res,{target:targetUrl})
});

app.use('/', connectHistoryApiFallback());
app.use('/',Express.static(path.join(__dirname,"..",'build')));

app.use(compression());
app.use(favicon(path.join(__dirname,'..','public','favicon.ico')));


//热更新
if(process.env.NODE_EVN!=='production'){
    const Webpack = require('webpack');
    const WebpackDevMiddleware = require('webpack-dev-middleware');
    const WebpackHotMiddleware = require('webpack-hot-middleware');
    const webpackConfig = require('../webpack.dev');

    const compiler = Webpack(webpackConfig);

    app.use(WebpackDevMiddleware(compiler, {
        publicPath: '/',
        stats: {colors: true},
        lazy: false,
        watchOptions: {
            aggregateTimeout: 300,
            poll: true
        },
    }));
    app.use(WebpackHotMiddleware(compiler));
}

app.listen(port,(err)=>{
    if(err){
        console.error(err)
    }else{
        console.log(`===>open http://${config.host}:${config.port} in a browser to view the app`);
    }
});

在生产环境下,前段部分页面的路由通过打包的文件加载

app.use('/',Express.static(path.join(__dirname,"..",'build')));

开发环境下,通过webpack-dev-middlewarewebpack-hot-middleware实现页面加载和热更新

if(process.env.NODE_EVN!=='production'){
    const Webpack = require('webpack');
    const WebpackDevMiddleware = require('webpack-dev-middleware');
    const WebpackHotMiddleware = require('webpack-hot-middleware');
    const webpackConfig = require('../webpack.dev');

    const compiler = Webpack(webpackConfig);

    app.use(WebpackDevMiddleware(compiler, {
        publicPath: '/',
        stats: {colors: true},
        lazy: false,
        watchOptions: {
            aggregateTimeout: 300,
            poll: true
        },
    }));
    app.use(WebpackHotMiddleware(compiler));
}

总结

到此,我们完成了webpack打包和启动文件配置,结合上一篇文章的内容,目前的项目文件地址在这里

使用方法:

git clone https://github.com/sam408130/react-blog.git
git checkout part3
npm install 
npm start

启动后,浏览器自动打开博客的首页:

屏幕快照 2017-11-02 下午6.48.42.png

下一节内容介绍如何使用redux,使用redux-saga处理异步请求的action,以及所有页面的数据请求和页面更新。

系列文章

React技术栈+Express+Mongodb实现个人博客
React技术栈+Express+Mongodb实现个人博客 -- Part 1 博客页面展示
React技术栈+Express+Mongodb实现个人博客 -- Part 2 后台管理页面
React技术栈+Express+Mongodb实现个人博客 -- Part 3 Express + Mongodb创建Server端
React技术栈+Express+Mongodb实现个人博客 -- Part 4 使用Webpack打包博客工程
React技术栈+Express+Mongodb实现个人博客 -- Part 5 使用Redux
React技术栈+Express+Mongodb实现个人博客 -- Part 6 部署

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容