EMP v1.8 配置优化详解

1,711 阅读1分钟

为了更直观地配置EMP 1.8之后把配置文件进行了TS改造,具体详情如下:

配置

packages/emp-cli/types/emp-config.d.ts

declare interface EMPConfig {
  /** webpack & webpack chain config method */
  webpack?: (o: EmpConfigI & EmpConfigIBase) => WebpackConfigI | Promise<WebpackConfigI>
  webpackChain?: (config: webpackChain, o: EmpConfigI) => void | Promise<any>
  /**
   * compile replace babel use swc or esbuild
   * 拓展 swc、build 替换 babel进行构建
   */
  compile?: Array<any>
  /**
   * react vue svetle and more
   * 拓展 js 框架支持
   */
  framework?: Array<any>
  /**
   * module federation config
   * module federation 设置
   */
  moduleFederation?: ModuleFederationType
  /**
   * global assets path
   * when output.publicPath=auto & use module federation,need setting this option
   * 当 output.publicPath=auto时 自定义静态文件路径
   */
  moduleGenerator?: ModuleGeneratorType
  /**
   * style command of emp
   * 命令行拓展
   */
  commander?: (program: Command) => void
  /**
   * before dev env=development server
   * emp dev 启动前执行
   */
  beforeDev?: (config: EmpConfigI) => void | Promise<any>
  /**
   * before build env=production server
   * emp build 启动前执行
   */
  beforeBuild?: (config: EmpConfigI) => void | Promise<any>
}

用例

emp-config.js

// 加入注释 让 配置支持 TS 提示
/**
 * @type {import('@efox/emp-cli').EMPConfig}
 */
module.exports = {
  // webpack 配置 默认 webpack 覆盖 webpack chain
  webpack() {
    return {
      devServer: {
        port:3333,
      },
    }
  },
  // 编译方式 如 esbuild 替代 babel 
  framework: [require('@efox/emp-esbuild')],
  // 框架 
  framework: [require('@efox/emp-vue2')],
  // webpack chain 配置 
  webpackChain(config) {
    config.plugin('html').tap(args => {
      args[0].files.publicPath = `http://localhost:3333`
      console.log(args)
      return args
    })
  },
  // module federation 独立配置 
  async moduleFederation() {
    return {
      name: 'demo2',
      filename: 'emp.js',
      remotes: {
        '@emp/demo1': 'demo1@http://localhost:8001/emp.js',
      },
      exposes: {
        './components/Hello': 'src/components/Hello',
        './helper': 'src/helper',
      },
      shared: {
        react: {eager: true, singleton: true, requiredVersion: '^17.0.1'},
        'react-dom': {eager: true, singleton: true, requiredVersion: '^17.0.1'},
      },
    }
  },
  // *** 当 output.publicPath=auto时 自定义静态文件路径
  // 建议 支持 module federation 模式下打开 auto
  // ===> 文件路径配置化 
  // 具体可以 参考 https://webpack.js.org/configuration/module/#modulegenerator
  moduleGenerator: {
    asset: {
      publicPath: '/', //默认是全局 
    },
  },
  // ===> 或者 
  moduleGenerator({webpackEnv}) {
    return webpackEnv === 'development' ? '/' : `http://localhost:8001/`
  },
}