jackieli123723 / jackieli123723.github.io

✅lilidong 个人博客
9 stars 0 forks source link

webpack4.x开发项目小结 #56

Open jackieli123723 opened 6 years ago

jackieli123723 commented 6 years ago

webpack4.x开发项目小结

webpack4.x是以项目根目录下的'./src'作为入口,但我们的项目中缺乏该路径,因此我们在根目录下创建src文件夹,事实上webpack4.x以'./src/index.js'作为入口,同时package.json中的字段"main"为 "index.js"

.babelrc编译

把es6编译为最新的es5兼容模式,同时高版本浏览器使用es6语法不用垫片功能

参考
npm install @babel/core @babel/register  @babel/preset-env --save-dev
注意webpack4使用的版本
https://www.npmjs.com/package/@babel/register

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "browsers": [
            "ios >= 9",
            "android >= 4"
          ]
        }
      }
    ]
  ]
}

编译命令和参数

- 我们如果需要配置webpack指令的其他参数,只需要在webpack –mode production/development后加上其他参数即可,如:

webpack --mode development --watch --progress --display-modules --colors --display-reasons

本例使用了--colors和 --module-bind js=babel-loader( 配合babel 将es6转成es5 超简单实例)

  "main": "index.js",
  "scripts": {
    "start": "npm run build && node index.js",
    "dev": "webpack --mode development --colors  && nodemon index.js",
    "build": "webpack --mode production --colors --module-bind js=babel-loader"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0-beta.42",
    "@babel/preset-env": "^7.0.0-beta.42",
    "@babel/register": "^7.0.0-beta.42",
    "babel-loader": "^8.0.0-beta",
    "webpack": "^4.0.1",
    "webpack-cli": "^2.0.9"
  },
  "dependencies": {
    "express": "^4.16.3",
    "opn": "^5.3.0",
    "compression": "^1.7.1",
    "helmet": "^3.9.0"
  }

- 另外dev 和 build的区别是压缩比例 main.js 的混合压缩,在配合node的压缩和帽子戏法可以把资源进一步gzip压缩50%(实测可能有出入)

npm run build


> webpack --mode production --colors --module-bind js=babel-loader

Hash: d32cf3648ed5058dbac8
Version: webpack 4.2.0
Time: 1563ms
Built at: 2018-3-22 13:54:16
  Asset      Size  Chunks             Chunk Names
main.js  34.3 KiB       0  [emitted]  main
Entrypoint main = main.js

npm run dev

> webpack --mode development --colors  && nodemon index.js

Hash: e1467fbaa56e35b838da
Version: webpack 4.2.0
Time: 215ms
Built at: 2018-3-22 14:16:32
  Asset      Size  Chunks             Chunk Names
main.js  78.8 KiB    main  [emitted]  main

node部署es5和es6的两种方式

- 使用es5的方式就直接用const xxx = require('xxx'),可以直接打包编译无需额外工作

- 使用es6的方式使用import xxx from 'xxx'的话不能直接编译,报错SyntaxError: Unexpected token import

要使用包裹层编译

老的编译可以看ng5项目es6方式 koa-deploy-import-babel.js.

require("@babel/register")({
   "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "browsers": [
            "ios >= 9",
            "android >= 4"
          ]
        }
      }
    ]
  ]
});
require("./import-index.js");
//index.js

//way1
const port = process.env.PORT || 8082
const host = `http://localhost:${port}`
const express = require('express')
const path = require('path')
const opn = require('opn')
const app  = express()
const helmet = require('helmet')
const compression = require('compression')
app.use(helmet())
app.use(compression())
app.use('/assets', express.static(path.resolve(__dirname, './assets')))
app.use('/dist', express.static(path.resolve(__dirname, './dist')))

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, './index.html'));
})

app.listen(port, () => {
  console.log(`服务启动端口 ${host}`)
  opn(host)
})

//way2
// require("@babel/register")({
//    "presets": [
//     [
//       "@babel/preset-env",
//       {
//         "targets": {
//           "browsers": [
//             "ios >= 9",
//             "android >= 4"
//           ]
//         }
//       }
//     ]
//   ]
// });
// require("./import-index.js");

//import-index.js

"use strict";
const port = process.env.PORT || 8082
const host = `http://localhost:${port}`
import express from 'express';
import path from 'path'
import opn from 'opn'
import helmet from 'helmet'
import compression from 'compression'
const app = express()

app.use(helmet())
app.use(compression())

app.use('/assets', express.static(path.resolve(__dirname, './assets')))
app.use('/dist', express.static(path.resolve(__dirname, './dist')))

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, './index.html'));
})

app.listen(port, () => {
  console.log(`服务启动端口 ${host}`)
  opn(host)
})
jackieli123723 commented 6 years ago

另外用koa跨域部署

import koa from 'koa';
import serve from 'koa-static';
import cors from 'koa2-cors';
import 'babel-polyfill';

import router from './src/router';
import './src/schedule';

const app = new koa();

app.use(cors());
router.init(app);
app.use(serve('client'));

/*eslint no-console: 0 */
console.warn('server is running at : localhost:3333');
app.listen(3333);
jackieli123723 commented 6 years ago

一份详细的webpack4配置

const path = require('path');
const webpack = require("webpack");

module.exports = {
  entry: {
    index: './src/index.js',
    vendor: ['lodash']
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    })
  ],
  optimization: {
    splitChunks: {
      chunks: "initial",         // 必须三选一: "initial" | "all"(默认就是all) | "async"
      minSize: 0,                // 最小尺寸,默认0
      minChunks: 1,              // 最小 chunk ,默认1
      maxAsyncRequests: 1,       // 最大异步请求数, 默认1
      maxInitialRequests: 1,    // 最大初始化请求书,默认1
      name: () => {},              // 名称,此选项课接收 function
      cacheGroups: {                 // 这里开始设置缓存的 chunks
        priority: "0",                // 缓存组优先级 false | object |
        vendor: {                   // key 为entry中定义的 入口名称
          chunks: "initial",        // 必须三选一: "initial" | "all" | "async"(默认就是异步)
          test: /react|lodash/,     // 正则规则验证,如果符合就提取 chunk
          name: "vendor",           // 要缓存的 分隔出来的 chunk 名称
          minSize: 0,
          minChunks: 1,
          enforce: true,
          maxAsyncRequests: 1,       // 最大异步请求数, 默认1
          maxInitialRequests: 1,    // 最大初始化请求书,默认1
          reuseExistingChunk: true   // 可设置是否重用该chunk(查看源码没有发现默认值)
        }
      }
    }
  },
  output: {
    path: path.join(__dirname, "dist"),
    // filename: "[name].js",
    // chunkFilename: "[name].chunk.js"
  }
};