大前端學習第5課: Koa項目工程化2

在前面的課程中,簡單的配置了一下webpack,以及介紹了一些nodejs的調試技巧。這節課信息量仍是比較大的。主要講了如下內容:javascript

目錄

  1. npm-check-updates的使用
  2. koa-compose的使用
  3. 如何分離webpack的生成環境和開發環境
  4. Terser的使用
  5. 生產環境中,koa的目錄結構
  6. Koa-compress的使用

npm-check-updates

Find newer versions of dependencies than what your package.json or bower.json allows 查找package.json更新的依賴項前端

使用很簡單。java

安裝: npm install npm-check-updates -gnode

升級:ncu -uwebpack

刪除:rm -rf node_moduleses6

安裝:npm installweb

koa-compose

Compose Koa middleware : 組裝koa的中間件npm

install: npm i koa-composejson

// 這種寫法將被淘汰
app.use(helmet());
app.use(statics(path.join(__dirname, '../public')));
app.use(router());
複製代碼
// 使用compose
const middleware = compose([
  koaBody(),
  statics(path.join(__dirname, '../public')),
  cors(),
  jsonutil({ pretty: false, param: 'pretty' }),
  helmet()
])

app.use(middleware);
app.use(router());

複製代碼

如何分離webpack的生成環境和開發環境

一般來講,webpack的配置文件會有3個。分別是:api

  1. webpack.config.base.js
  2. webpack.config.dev.js
  3. webpack.config.prod.js

首先: webpack.config.base.js裏面的內容見個人 另一篇博客.

配置definePlugin

The DefinePlugin allows you to create global constants which can be configured at compile time. DefinePlugin容許您建立可在編譯時配置的全局常量。

// webpack.config.base.js
import webpack from 'webpack';
plugin: [
  new CleanWebpackPlugin(),
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod') ? "'production'" : "'development'"
    }
  })
],
複製代碼

使用webpack-merge合併webpack配置

Variant of merge that's useful for webpack configuration: 它對合並webpack的變量頗有用。

// webpack.config.dev.js
const webpaceMerge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.config.base');

const webpackConfig = {
  mode: 'development',
  devtool: 'eval-source-map',
  status: { children: false }
}

module.exports = webpaceMerge(baseWebpackConfig, webpackConfig);
複製代碼

使用Terser壓縮文件

This plugin uses terser to minify your JavaScript.

webpack4建議使用terser

使用: npm install terser-webpack-plugin

const webpaceMerge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.config.base');
const terserWebpackPlugin = require('terser-webpack-plugin');


const webpackConfig = webpaceMerge(baseWebpackConfig, {
  mode: "production",
  stats: { children: fasle, warnings: false },
  optimization: {
    minimizer: [
      new terserWebpackPlugin({
        terserOptions: {
          warnings: false,
          compress: {
            warnings: false,
            drop_console: false,
            dead_code: true,
            drop_debugger: true
          },
          output: {
            comments: false,
            beautify: false,
          },
          mangle: true,
        },
        parallel: true,
        sourceMap: false
      })
    ]
  }
})

module.exports = webpackConfig;
複製代碼

使用spilitChunks

Originally, chunks (and modules imported inside them) were connected by a parent-child relationship in the internal webpack graph. The CommonsChunkPlugin was used to avoid duplicated dependencies across them, but further optimizations were not possible. spilitChunks 能夠避免重複依賴

splitChunks: {
  cacheGroups: {
    commons: {
      name: 'commons',
      chunks: 'initial',
      minChunks: 3
    }
  }
}
複製代碼

使用utils配置path

const path = require('path')

exports.resolve = function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

exports.APP_PATH = exports.resolve('src')
exports.DIST_PATH = exports.resolve('dist')

複製代碼

最後, 配置package.json

"scripts": {
    "start": "nodemon src/index.js",
    "start:es6": "nodemon --exec babel-node src/index.js",
    "build": "cross-env NODE_ENV=prod webpack --config config/webpack.config.prod.js",
    "dev": "cross-env NODE_ENV=dev nodemon --exec babel-node --inspect ./src/index.js",
    "clean": "rimraf dist"
  },
複製代碼

rimraf: 刪除dist目錄,相似rm -rf

生產環境中,koa的目錄結構

// api=> demoController.js
class DemoController {
  constructor() { }
  async demo(ctx) {
    ctx.body = {
      msg: 'body message!!!',
    }
  }
}

export default new DemoController()
複製代碼
//demoRorouter.js
import Router from 'koa-router';
import demoController from '../api/demoController';

const router = new Router();

router.get('/demo', demoController.demo);

export default router;
複製代碼
// routes.js
import combineRoutes from 'koa-combine-routers'

import demoRouter from './demoRouter'

export default combineRoutes(demoRouter)
複製代碼

Koa Compress

Compress middleware for Koa: koa的壓縮中間件

import compress from 'koa-compress';
//index.js
if(!isDevMode) {
  app.use(compress())
}
複製代碼

我是海明月,前端小學生。

相關文章
相關標籤/搜索