天天看點

基于webpack5封裝的cli工具packx

安裝

用 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,
  },
}, () => {
    // 建構結束處理
  });

           

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

基于webpack5封裝的cli工具packx

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

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