web优化 之 更优引入

本文Demo的完整工程代码, 参考alternative-moment

目录

  • 开始

  • moment

  • date-fns

  • fecha

  • spacetime

  • 小结

开始

dva new alternative-moment
npm run build
File sizes after gzip:

  88.61 KB  dist/index.js
  316 B     dist/index.css

moment

cnpm i --save moment
vim src/routes/IndexPage.js
import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import styles from './IndexPage.css';

function IndexPage() {
  return (
    
{moment().format('MMMM Do YYYY, h:mm:ss a')}

Yay! Welcome to dva!

); } IndexPage.propTypes = { }; export default connect()(IndexPage);
npm run build
File sizes after gzip:

  153.22 KB  dist/index.js
  316 B      dist/index.css

date-fns

cnpm i --save date-fns

cnpm i --save-dev babel-plugin-date-fns
vim .roadhogrc
{
  "entry": "src/index.js",
  "env": {
    "development": {
      "extraBabelPlugins": [
        "dva-hmr",
        "transform-runtime",
        "date-fns"
      ]
    },
    "production": {
      "extraBabelPlugins": [
        "transform-runtime",
        "date-fns"
      ]
    }
  }
}
vim src/routes/IndexPage.js
import React from 'react';
import { connect } from 'dva';
import { format } from 'date-fns';
import styles from './IndexPage.css';

function IndexPage() {
  return (
    
{format(new Date(), 'MMMM Do YYYY, h:mm:ss a')}

Yay! Welcome to dva!

); } IndexPage.propTypes = { }; export default connect()(IndexPage);
npm run build
File sizes after gzip:

  91.46 KB  dist/index.js
  316 B     dist/index.css

关于date-fns详细介绍 参考web优化 之 模块化引入

fecha

cnpm i --save fecha
vim src/routes/IndexPage.js
import React from 'react';
import { connect } from 'dva';
import fecha from 'fecha';
import styles from './IndexPage.css';

function IndexPage() {
  return (
    
{fecha.format(new Date(), 'MMMM Do YYYY, h:mm:ss a')}

Yay! Welcome to dva!

); } IndexPage.propTypes = { }; export default connect()(IndexPage);
npm run build
File sizes after gzip:

  90.33 KB  dist/index.js
  316 B     dist/index.css

spacetime

cnpm i --save spacetime
vim src/routes/IndexPage.js
import React from 'react';
import { connect } from 'dva';
import spacetime from 'spacetime';
import styles from './IndexPage.css';

function IndexPage() {
  return (
    
{spacetime.now().format('full')}

Yay! Welcome to dva!

); } IndexPage.propTypes = { }; export default connect()(IndexPage);
npm run build
File sizes after gzip:

  100.08 KB  dist/index.js
  316 B      dist/index.css

小结

包大小(KB) 评价
dva 88.61 N/A
dva+moment 153.22 ★★★★
dva+date-fns 91.46 ★★★★★
dva+fecha 90.33 ★★★
dva+spacetime 100.08 ★★

说明: (1) date-fns基于模块化引入 (2) 包大小是指gzip压缩后

参考

  • Webpack 打包优化之体积篇

  • Modularize moment.js, make the core as light as possible

  • how-to-optimize-momentjs-with-webpack

  • momentjs docs

  • Moment.js中文网

  • date-fns docs

  • date-fns 轻量级的 JavaScript 日期库

  • spacetime

  • fecha

更多文章, 请支持我的个人博客

你可能感兴趣的:(web优化 之 更优引入)