All files / builder/application webpack-configuration-change.service.ts

98.83% Statements 85/86
82.66% Branches 62/75
100% Functions 23/23
98.83% Lines 85/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265            1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x                       1x 1x         9x         9x 9x 9x     9x                               9x                             9x 9x   9x     9x 9x 9x 9x 9x 9x 9x     9x               9x 1x 1x       9x     9x 9x 19x   10x 10x         9x   9x 9x 321x 4763x   321x 221x   100x       9x       9x       862x 11701x     842x   20x   9x     3223x 3223x                         9x 9x 321x 4763x   100x       281x   40x   9x 10x     40x     9x     9x     9x       9x           9x       9x               9x                                     9x 8x       9x     9x   105x     9x   9x 9x 9x                        
import type { BuilderContext } from '@angular-devkit/architect';
import {
  AssetPattern,
  BrowserBuilderOptions,
  KarmaBuilderOptions,
} from '@angular-devkit/build-angular';
import { normalize } from '@angular-devkit/core';
import * as path from 'path';
import { filter } from 'rxjs/operators';
import { Injectable, Injector } from 'static-injector';
import * as webpack from 'webpack';
import { DefinePlugin } from 'webpack';
import { BootstrapAssetsPlugin } from 'webpack-bootstrap-assets-plugin';
import { LIBRARY_OUTPUT_ROOTDIR } from '../library';
import { BuildPlatform } from '../platform/platform';
import type { PlatformType } from '../platform/platform';
import { LibraryTemplateScopeService } from './library-template-scope.service';
import { DynamicLibraryComponentEntryPlugin } from './plugin/dynamic-library-entry.plugin';
import { DynamicWatchEntryPlugin } from './plugin/dynamic-watch-entry.plugin';
import { ExportMiniProgramAssetsPlugin } from './plugin/export-mini-program-assets.plugin';
import { TS_CONFIG_TOKEN } from './token';
import type { PagePattern } from './type';
 
type OptimizationOptions = NonNullable<webpack.Configuration['optimization']>;
type OptimizationSplitChunksOptions = Exclude<
  OptimizationOptions['splitChunks'],
  false | undefined
>;
type OptimizationSplitChunksCacheGroup = Exclude<
  NonNullable<OptimizationSplitChunksOptions['cacheGroups']>[''],
  false | string | Function | RegExp
>;
@Injectable()
export class WebpackConfigurationChangeService {
  exportMiniProgramAssetsPluginInstance!: ExportMiniProgramAssetsPlugin;
  private buildPlatform!: BuildPlatform;
  private entryList!: PagePattern[];
  constructor(
    private options: (BrowserBuilderOptions | KarmaBuilderOptions) & {
      pages: AssetPattern[];
      components: AssetPattern[];
      platform: PlatformType;
    },
    private context: BuilderContext,
    private config: webpack.Configuration,
    private injector: Injector
  ) {}
  init() {
    this.injector = Injector.create({
      parent: this.injector,
      providers: [
        { provide: ExportMiniProgramAssetsPlugin },
        { provide: LibraryTemplateScopeService },
        {
          provide: TS_CONFIG_TOKEN,
          useValue: path.resolve(
            this.context.workspaceRoot,
            this.options.tsConfig
          ),
        },
        {
          provide: DynamicWatchEntryPlugin,
          deps: [BuildPlatform],
          useFactory: (buildPlatform: BuildPlatform) => {
            return new DynamicWatchEntryPlugin(
              {
                pages: this.options.pages,
                components: this.options.components,
                workspaceRoot: normalize(this.context.workspaceRoot),
                context: this.context,
                config: this.config,
              },
              buildPlatform
            );
          },
        },
        { provide: DynamicLibraryComponentEntryPlugin },
      ],
    });
    this.buildPlatform = this.injector.get(BuildPlatform);
    this.buildPlatform.fileExtname.config =
      this.buildPlatform.fileExtname.config || '.json';
    this.config.output!.globalObject = this.buildPlatform.globalObject;
  }
  async change() {
    this.buildPlatformCompatible();
    this.exportAssets();
    await this.pageHandle();
    this.addLoader();
    this.globalVariableChange();
    this.changeStylesExportSuffix();
    this.config.plugins?.push(
      this.injector.get(DynamicLibraryComponentEntryPlugin)
    );
    this.config.plugins?.push(
      new webpack.NormalModuleReplacementPlugin(
        /^angular-miniprogram\/platform\/wx$/,
        `angular-miniprogram/platform/${this.buildPlatform.packageName}`
      )
    );
  }
  private buildPlatformCompatible() {
    if (this.buildPlatform.packageName == 'zfb') {
      this.config.resolve?.conditionNames?.shift();
      this.config.resolve?.mainFields?.shift();
    }
  }
  private async pageHandle() {
    const dynamicWatchEntryInstance = this.injector.get(
      DynamicWatchEntryPlugin
    );
    await dynamicWatchEntryInstance.init();
    dynamicWatchEntryInstance.entryPattern$
      .pipe(filter((item) => !!item))
      .subscribe((result) => {
        this.entryList = [...result!.pageList, ...result!.componentList];
        this.exportMiniProgramAssetsPluginInstance.setEntry(
          result!.pageList,
          result!.componentList
        );
      });
    this.config.plugins?.push(dynamicWatchEntryInstance);
    // 出口
    const oldFileName = this.config.output!.filename as string;
    this.config.output!.filename = (chunkData) => {
      const page = this.entryList.find(
        (item) => item.entryName === chunkData.chunk!.name
      );
      if (page) {
        return page.outputFiles.logic;
      }
      return oldFileName;
    };
    // 共享依赖
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const oldChunks = (this.config.optimization!.splitChunks as any).cacheGroups
      .defaultVendors.chunks;
    (
      (
        this.config.optimization!
          .splitChunks! as unknown as OptimizationSplitChunksOptions
      ).cacheGroups!.defaultVendors as OptimizationSplitChunksCacheGroup
    ).chunks = (chunk) => {
      if (
        this.entryList.find((item) => item.entryName === chunk.name) ||
        chunk.name!.startsWith(`${LIBRARY_OUTPUT_ROOTDIR}/`)
      ) {
        return true;
      }
      return oldChunks(chunk);
    };
    ((this.config.optimization!.splitChunks as OptimizationSplitChunksOptions)
      .cacheGroups!['moduleChunks'] as OptimizationSplitChunksCacheGroup) = {
      test: (module: webpack.NormalModule) => {
        const name = module.nameForCondition();
        return (
          (name &&
            name.endsWith('.ts') &&
            !/[\\/]node_modules[\\/]/.test(name)) ||
          name?.includes('angular-miniprogram\\dist')
        );
      },
      minChunks: 2,
      minSize: 0,
      name: 'module-chunk',
      chunks: 'all',
    };
    // 出口保留必要加载
    const assetsPlugin = new BootstrapAssetsPlugin();
    assetsPlugin.hooks.removeChunk.tap('pageHandle', (chunk) => {
      if (
        this.entryList.some((page) => page.entryName === chunk.name) ||
        [...chunk.files].some((file) =>
          file.endsWith(this.buildPlatform.fileExtname.style)
        ) ||
        chunk.name!.startsWith(`${LIBRARY_OUTPUT_ROOTDIR}/`)
      ) {
        return true;
      }
      return false;
    });
    assetsPlugin.hooks.emitAssets.tap('pageHandle', (object, json) => {
      return {
        'app.js':
          this.buildPlatform.importTemplate +
          json.scripts.map((item) => `require('./${item.src}')`).join(';'),
      };
    });
    this.config.plugins!.push(assetsPlugin);
  }
  private exportAssets() {
    this.exportMiniProgramAssetsPluginInstance = this.injector.get(
      ExportMiniProgramAssetsPlugin
    );
    this.config.plugins!.unshift(this.exportMiniProgramAssetsPluginInstance);
  }
 
  private addLoader() {
    this.config.module!.rules!.unshift({
      test: /\.ts$/,
      loader: require.resolve(
        path.join(__dirname, './loader/component-template.loader')
      ),
    });
    this.config.module?.rules?.unshift({
      test: /\.mjs$/,
      loader: require.resolve(path.join(__dirname, './loader/library.loader')),
    });
    this.config.module?.rules?.unshift({
      test: /\.mjs$/,
      loader: require.resolve(
        path.join(__dirname, './loader/library-template.loader')
      ),
    });
  }
  private globalVariableChange() {
    const defineObject: Record<string, string> = {
      global: `${this.buildPlatform.globalObject}.__global`,
      window: `${this.buildPlatform.globalVariablePrefix}`,
      globalThis: `${this.buildPlatform.globalVariablePrefix}`,
      Zone: `${this.buildPlatform.globalVariablePrefix}.Zone`,
      setTimeout: `${this.buildPlatform.globalVariablePrefix}.setTimeout`,
      clearTimeout: `${this.buildPlatform.globalVariablePrefix}.clearTimeout`,
      setInterval: `${this.buildPlatform.globalVariablePrefix}.setInterval`,
      clearInterval: `${this.buildPlatform.globalVariablePrefix}.clearInterval`,
      Promise: `${this.buildPlatform.globalVariablePrefix}.Promise`,
      Reflect: `${this.buildPlatform.globalVariablePrefix}.Reflect`,
      requestAnimationFrame: `${this.buildPlatform.globalVariablePrefix}.requestAnimationFrame`,
      cancelAnimationFrame: `${this.buildPlatform.globalVariablePrefix}.cancelAnimationFrame`,
      performance: `${this.buildPlatform.globalVariablePrefix}.performance`,
      navigator: `${this.buildPlatform.globalVariablePrefix}.navigator`,
      wx: this.buildPlatform.globalObject,
      miniProgramPlatform: `"${this.buildPlatform.globalObject}"`,
      queueMicrotask:`${this.buildPlatform.globalVariablePrefix}.queueMicrotask`
    };
    if (this.config.mode === 'development') {
      defineObject[
        'ngDevMode'
      ] = `${this.buildPlatform.globalObject}.__global.ngDevMode`;
    }
    this.config.plugins!.push(new DefinePlugin(defineObject));
  }
  private changeStylesExportSuffix() {
    const index = this.config.plugins!.findIndex(
      (plugin) =>
        Object.getPrototypeOf(plugin).constructor.name ===
        'MiniCssExtractPlugin'
    );
    Eif (index > -1) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const pluginInstance = this.config.plugins![index] as any;
      const pluginPrototype = Object.getPrototypeOf(pluginInstance);
      this.config.plugins?.splice(
        index,
        1,
        new pluginPrototype.constructor({
          filename: 'app' + this.buildPlatform.fileExtname.style,
        })
      );
    } else {
      throw new Error('没有找到MiniCssExtractPlugin插件,无法修改生成style');
    }
  }
}