基於webpack5封裝的cli工具packx

  • 2021 年 6 月 20 日
  • 筆記

安裝

npm / yarn 安裝:

$ npm install -D packx
$ yarn add -D packx

特性

  1. 基於 webpack5
  2. 支持 less,sass
  3. 支持 spa/mpa
  4. 支持 typescript
  5. 支持自定義html模板和自動生成 html入口
  6. 支持 react hmr
  7. 支持擴展 postcss, 比如 px2rem, px2viewport
  8. 支持自定義配置packx.config.js,覆蓋默認webpack配置 (基於 webpack merge 算法)
  9. 支持 node api 調用和命令行調用
  10. 支持ssr

用法

  • 開發 packx start [-p port]
  • 構建 packx build [-p publicPath]
  • 自定義 packx run [–build],配置 packx.config.js
  • js api 調用
  • ssr

入口在 ./src 目錄下,比如./src/index.jsx

--src
  - index.jsx;

運行 packx start

入口在 ./src/page/ 目錄下,比如./src/page/index.tsx

--src 
  --page
     -index.tsx;

運行 packx start page

入口 html, 如果項目不包含 index.html ,默認會生成 index.html,可以自定義 html 結構
<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta
      name="viewport"
      content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,minimal-ui,viewport-fit=cover"
    />
    <meta name="format-detection" content="telephone=no, email=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-touch-fullscreen" content="yes" />
    <title></title>
  </head>
  <body style="font-size: 14px">
    <div id="root"></div>
  </body>
</html>

擴展 postcss 插件

項目根目錄添加 postcss.config.js, 以添加 px2viewport 為例

module.exports = (ctx) => {
  if (!/node_modules/.test(ctx.file)) {
    ctx.options.plugins.push([
      require('postcss-px-to-viewport'),
      {
        unitToConvert: 'px',
        viewportWidth: 375,
        unitPrecision: 5,
        propList: ['*'],
        viewportUnit: 'vw',
        fontViewportUnit: 'vw',
        selectorBlackList: ['ignore'],
        minPixelValue: 1,
        mediaQuery: false,
        replace: true,
        exclude: [/node_modules/],
        include: undefined,
        landscape: false,
        landscapeUnit: 'vw',
      },
    ]);
  }
};

packx run 通過 packx.config.js 自定義配置

注意,除了 entry 限制為 object 外, 配置項和 webpack 配置一致
下面通過自定義配置 packx.config.js 實現了 mpa 項目的打包

const path = require('path');

module.exports = {
  entry: {
    h5: './src/h5/index',
    pc: './src/pc/index',
  },
  output: {
    path: path.resolve(__dirname, './dist/packx-demo'),
    publicPath: '',
  },
};
  • 開發 packx run
  • 構建 packx run –build

node 命令行用法

packx 默認導出了一個 nodeApi, 函數簽名如下, Configuration 為 webpack 配置對象

export default function nodeApi(isDev: boolean, config: Configuration, callback?: () => void): void;
const { default: pack } = require('packx');
...

pack(isDev, {
  entry: {
    index: `./src/index`,
  },
  devServer: {
    port: 3000
  },
  output: {
    path: getDist('dist'),
    publicPath,
  },
}, () => {
    // 構建結束處理
  });

項目結構和打包輸出如下圖

structure.png

ssr

ssr和上述使用參考packx-demo庫

項目代碼參考 //github.com/leonwgc/packx-demo