大前端学习第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())
}
复制代码

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

相关文章
相关标签/搜索