注意

  • 弃用 npm run build & npm run dev & npm run dll
  • 改成 box build & box dev & box dll
  • link npm link 将 box 命令链接到全局

本章内容

  1. 使用
  2. 改造为脚手架
  3. 多页面配置

使用

box build # 不加参数则会编译所有页面,并清空 distbox dev   # 默认编译 index 页面

参数

# index2 是指定编译的页面。不会清空 dist# report 开启打包分析box build index2 --reportbox dev index2 --report

改造为脚手架

分成三个命令,进行不同操作

  • build
  • dev
  • dll
webpack 多页面配置-青梅煮码

bin/box.js

#!/usr/bin/env node

const chalk = require("chalk");
const program = require("commander");
const packageConfig = require("../package.json");
const { cleanArgs } = require("../lib");
const path = require("path");
const __name__ = `build,dev,dll`;

let boxConf = {};
let lock = false;

try {
  boxConf = require(path.join(process.cwd(), "box.config.js"))();
} catch (error) {}

program
  .usage("<command> [options]")
  .version(packageConfig.version)
  .command("build [app-page]")
  .description(`构建开发环境`)
  .option("-r, --report", "打包分析报告")
  .option("-d, --dll", "合并差分包")
  .action(async (name, cmd) => {
    const options = cleanArgs(cmd);
    const args = Object.assign(options, { name }, boxConf);
    if (lock) return;
    lock = true;
    if (boxConf.pages) {
      Object.keys(boxConf.pages).forEach(page => {
        args.name = page;
        require("../build/build")(args);
      });
    } else {
      require("../build/build")(args);
    }
  });

program
  .usage("<command> [options]")
  .version(packageConfig.version)
  .command("dev [app-page]")
  .description(`构建生产环境`)
  .option("-d, --dll", "合并差分包")
  .action(async (name, cmd) => {
    const options = cleanArgs(cmd);
    const args = Object.assign(options, { name }, boxConf);
    if (lock) return;
    lock = true;
    require("../build/dev")(args);
  });

program
  .usage("<command> [options]")
  .version(packageConfig.version)
  .command("dll [app-page]")
  .description(`编译差分包`)
  .action(async (name, cmd) => {
    const options = cleanArgs(cmd);
    const args = Object.assign(options, { name }, boxConf);
    if (lock) return;
    lock = true;
    require("../build/dll")(args);
  });

program.parse(process.argv).args && program.parse(process.argv).args[0];
program.commands.forEach(c => c.on("--help", () => console.log()));

if (process.argv[2] && !__name__.includes(process.argv[2])) {
  console.log();
  console.log(chalk.red(`  没有找到 ${process.argv[2]} 命令`));
  console.log();
  program.help();
}

if (!process.argv[2]) {
  program.help();
}

多页面配置

box.config.js

module.exports = function(config) {
  return {
    entry: "src/main.js", // 默认入口
    dist: "dist", // 默认打包目录
    publicPath: "/",
    port: 8888,
    pages: {
      index: {
        entry: "src/main.js",
        template: "public/index.html",
        filename: "index.html"
      },
      index2: {
        entry: "src/main.js",
        template: "public/index2.html",
        filename: "index2.html"
      }
    },
    chainWebpack(config) {}
  };
};