mfsu.js 13.8 KB
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = _default;
exports.getMfsuPath = exports.checkConfig = void 0;

function _react() {
  const data = _interopRequireDefault(require("react"));

  _react = function _react() {
    return data;
  };

  return data;
}

function _types() {
  const data = require("@umijs/types");

  _types = function _types() {
    return data;
  };

  return data;
}

function _utils() {
  const data = require("@umijs/utils");

  _utils = function _utils() {
    return data;
  };

  return data;
}

function _assert() {
  const data = _interopRequireDefault(require("assert"));

  _assert = function _assert() {
    return data;
  };

  return data;
}

function _fs() {
  const data = require("fs");

  _fs = function _fs() {
    return data;
  };

  return data;
}

function _mime() {
  const data = _interopRequireDefault(require("mime"));

  _mime = function _mime() {
    return data;
  };

  return data;
}

function _path() {
  const data = require("path");

  _path = function _path() {
    return data;
  };

  return data;
}

function _url() {
  const data = _interopRequireDefault(require("url"));

  _url = function _url() {
    return data;
  };

  return data;
}

function _webpack() {
  const data = _interopRequireDefault(require("webpack"));

  _webpack = function _webpack() {
    return data;
  };

  return data;
}

var _babelImportRedirectPlugin = _interopRequireDefault(require("./babel-import-redirect-plugin"));

var _constants = require("./constants");

var _DepBuilder = _interopRequireDefault(require("./DepBuilder"));

var _DepInfo = _interopRequireDefault(require("./DepInfo"));

var _getUmiRedirect = require("./getUmiRedirect");

var _utils2 = require("./utils");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

const debug = (0, _utils().createDebug)('umi:mfsu');

const checkConfig = api => {
  const mfsu = api.config.mfsu; // .mfsu directory do not match babel-loader

  if (mfsu && mfsu.development && mfsu.development.output) {
    (0, _assert().default)(/\.mfsu/.test(mfsu.development.output), `[MFSU] mfsu.development.output must match /\.mfsu/.`);
  }

  if (mfsu && mfsu.production && mfsu.production.output) {
    (0, _assert().default)(/\.mfsu/.test(mfsu.production.output), `[MFSU] mfsu.production.output must match /\.mfsu/.`);
  }
};

exports.checkConfig = checkConfig;

const getMfsuPath = (api, {
  mode
}) => {
  if (mode === 'development') {
    var _api$userConfig$mfsu, _api$userConfig$mfsu$;

    const configPath = (_api$userConfig$mfsu = api.userConfig.mfsu) === null || _api$userConfig$mfsu === void 0 ? void 0 : (_api$userConfig$mfsu$ = _api$userConfig$mfsu.development) === null || _api$userConfig$mfsu$ === void 0 ? void 0 : _api$userConfig$mfsu$.output;
    return configPath ? (0, _path().join)(api.cwd, configPath) : (0, _path().join)(api.paths.absTmpPath, '.cache', '.mfsu');
  } else {
    var _api$userConfig$mfsu2, _api$userConfig$mfsu3;

    const configPath = (_api$userConfig$mfsu2 = api.userConfig.mfsu) === null || _api$userConfig$mfsu2 === void 0 ? void 0 : (_api$userConfig$mfsu3 = _api$userConfig$mfsu2.production) === null || _api$userConfig$mfsu3 === void 0 ? void 0 : _api$userConfig$mfsu3.output;
    return configPath ? (0, _path().join)(api.cwd, configPath) : (0, _path().join)(api.cwd, './.mfsu-production');
  }
};

exports.getMfsuPath = getMfsuPath;

function _default(api) {
  const webpackAlias = {};
  const webpackExternals = {};
  let depInfo;
  let depBuilder;
  let mode = 'development';
  api.onStart( /*#__PURE__*/function () {
    var _ref = _asyncToGenerator(function* ({
      name,
      args
    }) {
      checkConfig(api);

      if (name === 'build') {
        mode = 'production'; // @ts-ignore
      } else if (name === 'mfsu' && args._[1] === 'build' && args.mode) {
        // umi mfsu build --mode
        // @ts-ignore
        mode = args.mode || 'development';
      }

      (0, _assert().default)(['development', 'production'].includes(mode), `[MFSU] Unsupported mode ${mode}, expect development or production.`);
      debug(`mode: ${mode}`);
      const tmpDir = getMfsuPath(api, {
        mode
      });
      debug(`tmpDir: ${tmpDir}`);

      if (!(0, _fs().existsSync)(tmpDir)) {
        _utils().mkdirp.sync(tmpDir);
      }

      depInfo = new _DepInfo.default({
        tmpDir,
        mode,
        api,
        cwd: api.cwd,
        webpackAlias
      });
      debug('load cache');
      depInfo.loadCache();
      depBuilder = new _DepBuilder.default({
        tmpDir,
        mode,
        api
      });
    });

    return function (_x) {
      return _ref.apply(this, arguments);
    };
  }());
  api.modifyConfig({
    fn(memo) {
      return _objectSpread(_objectSpread({}, memo), {}, {
        // Always enable dynamicImport when mfsu is enabled
        dynamicImport: memo.dynamicImport || {},
        // Lock chunks when mfsu is enabled
        chunks: ['umi']
      });
    },

    stage: Infinity
  });
  api.onBuildComplete( /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(function* ({
      err
    }) {
      if (err) return;
      debug(`build deps in production`);
      yield buildDeps();
    });

    return function (_x2) {
      return _ref2.apply(this, arguments);
    };
  }());
  api.onDevCompileDone( /*#__PURE__*/_asyncToGenerator(function* () {
    debug(`build deps in development`);
    yield buildDeps();
  }));
  api.describe({
    key: 'mfsu',
    config: {
      schema(joi) {
        return joi.object({
          development: joi.object({
            output: joi.string()
          }),
          production: joi.object({
            output: joi.string()
          }),
          exportAllMembers: joi.object()
        }).description('open mfsu feature');
      }

    },

    enableBy() {
      var _api$userConfig$mfsu4;

      return api.env === 'development' && api.userConfig.mfsu || api.env === 'production' && ((_api$userConfig$mfsu4 = api.userConfig.mfsu) === null || _api$userConfig$mfsu4 === void 0 ? void 0 : _api$userConfig$mfsu4.production) || process.env.ENABLE_MFSU;
    }

  });
  api.modifyBabelPresetOpts({
    fn: (opts, args) => {
      var _api$config$mfsu;

      return _objectSpread(_objectSpread({}, opts), args.mfsu ? {} : {
        importToAwaitRequire: {
          remoteName: _constants.MF_NAME,
          matchAll: true,
          webpackAlias,
          webpackExternals,
          alias: {
            [api.cwd]: '$CWD$'
          },
          // @ts-ignore
          exportAllMembers: (_api$config$mfsu = api.config.mfsu) === null || _api$config$mfsu === void 0 ? void 0 : _api$config$mfsu.exportAllMembers,

          onTransformDeps(opts) {
            const file = opts.file.replace(api.paths.absSrcPath + '/', '@/');

            if (process.env.MFSU_DEBUG && !opts.source.startsWith('.')) {
              if (process.env.MFSU_DEBUG === 'MATCHED' && !opts.isMatch) return;
              if (process.env.MFSU_DEBUG === 'UNMATCHED' && opts.isMatch) return;
              console.log(`> import ${_utils().chalk[opts.isMatch ? 'green' : 'red'](opts.source)} from ${file}, ${opts.isMatch ? 'MATCHED' : 'UNMATCHED'}`);
            } // collect dependencies


            if (opts.isMatch) {
              depInfo.addTmpDep(opts.source);
            }
          }

        }
      });
    },
    stage: Infinity
  });
  api.modifyBabelOpts({
    fn: function () {
      var _fn = _asyncToGenerator(function* (opts) {
        var _opts$presets;

        webpackAlias['core-js'] = (0, _path().dirname)(require.resolve('core-js/package.json'));
        webpackAlias['regenerator-runtime/runtime'] = require.resolve('regenerator-runtime/runtime'); // @ts-ignore

        const umiRedirect = yield (0, _getUmiRedirect.getUmiRedirect)(process.env.UMI_DIR); // 降低 babel-preset-umi 的优先级,保证 core-js 可以被插件及时编译

        (_opts$presets = opts.presets) === null || _opts$presets === void 0 ? void 0 : _opts$presets.forEach(preset => {
          if (preset instanceof Array && /babel-preset-umi/.test(preset[0])) {
            preset[1].env.useBuiltIns = false;
          }
        });
        opts.plugins = [// AntdIconPlugin,
        [_babelImportRedirectPlugin.default, {
          umi: umiRedirect,
          dumi: umiRedirect,
          '@alipay/bigfish': umiRedirect
        }], ...opts.plugins];
        return opts;
      });

      function fn(_x3) {
        return _fn.apply(this, arguments);
      }

      return fn;
    }(),
    stage: Infinity
  });
  api.addBeforeMiddlewares(() => {
    return (req, res, next) => {
      const _url$parse = _url().default.parse(req.url),
            pathname = _url$parse.pathname;

      if (!api.userConfig.mfsu || pathname === '/' || !(0, _fs().existsSync)((0, _path().join)(getMfsuPath(api, {
        mode: 'development'
      }), '.' + pathname))) {
        next();
      } else {
        const value = (0, _fs().readFileSync)((0, _path().join)(getMfsuPath(api, {
          mode: 'development'
        }), '.' + pathname), 'utf-8');
        res.setHeader('content-type', _mime().default.lookup((0, _path().parse)(pathname || '').ext)); // 排除入口文件,因为 hash 是入口文件控制的

        if (!/remoteEntry.js/.test(req.url)) {
          res.setHeader('cache-control', 'max-age=31536000,immutable');
        }

        res.send(value);
      }
    };
  }); // 修改 webpack 配置

  api.register({
    key: 'modifyBundleConfig',

    fn(memo, {
      type,
      mfsu
    }) {
      if (type === _types().BundlerConfigType.csr) {
        Object.assign(webpackAlias, memo.resolve.alias || {});
        (0, _assert().default)(typeof (memo.externals || {}) === 'object', `[MFSU] Unsupported externals config format, only support object, but got ${memo.externals}`);
        Object.assign(webpackExternals, memo.externals || {});

        if (!mfsu) {
          const remotePath = api.config.publicPath;
          memo.plugins.push(new (_webpack().default.container.ModuleFederationPlugin)({
            name: 'umi-app',
            remotes: {
              mf: 'mf@' + remotePath + _constants.MF_VA_PREFIX + 'remoteEntry.js'
            }
          }));
        }

        memo.experiments = _objectSpread(_objectSpread({}, memo.experiments), {}, {
          topLevelAwait: true
        });
      }

      return memo;
    },

    stage: Infinity
  });

  function buildDeps() {
    return _buildDeps.apply(this, arguments);
  } // npx umi mfsu build
  // npx umi mfsu build --mode production
  // npx umi mfsu build --mode development --force


  function _buildDeps() {
    _buildDeps = _asyncToGenerator(function* (opts = {}) {
      const _depInfo$loadTmpDeps = depInfo.loadTmpDeps(),
            shouldBuild = _depInfo$loadTmpDeps.shouldBuild;

      debug(`shouldBuild: ${shouldBuild}, force: ${opts.force}`);

      if (opts.force || shouldBuild) {
        yield depBuilder.build({
          deps: depInfo.data.deps,
          webpackAlias,

          onBuildComplete(err, stats) {
            debug(`build complete with err ${err}`);

            if (err || stats.hasErrors()) {
              return;
            }

            debug('write cache');
            depInfo.writeCache();

            if (mode === 'development') {
              const server = api.getServer();
              debug(`refresh server`);
              server.sockWrite({
                type: 'ok',
                data: {
                  reload: true
                }
              });
            }
          }

        });
      }

      if (mode === 'production') {
        // production 模式,build 完后将产物移动到 dist 中
        debug(`copy mf output files to dist`);
        (0, _utils2.copy)(depBuilder.tmpDir, (0, _path().join)(api.cwd, api.userConfig.outputPath || './dist'));
      }
    });
    return _buildDeps.apply(this, arguments);
  }

  api.registerCommand({
    name: 'mfsu',

    fn({
      args
    }) {
      return _asyncToGenerator(function* () {
        switch (args._[0]) {
          case 'build':
            console.log('[MFSU] build deps...');
            yield buildDeps({
              force: args.force
            });
            break;

          default:
            throw new Error(`[MFSU] Unsupported subcommand ${args._[0]} for mfsu.`);
        }
      })();
    }

  });
}