UNPKG

ts-paths-to-relative-path-rspack-plugin

Version:
62 lines (61 loc) 3.2 kB
import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path"; import * as __WEBPACK_EXTERNAL_MODULE_os__ from "os"; import * as __WEBPACK_EXTERNAL_MODULE_fs_extra__ from "fs-extra"; function _define_property(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; } const assertionTsConfigPath = (tsConfigPath)=>{ if (!tsConfigPath) throw new Error('tsConfigPath is required'); if (!__WEBPACK_EXTERNAL_MODULE_path__["default"].isAbsolute(tsConfigPath)) throw new Error(`tsConfigPath must be an absolute path. actual path:${tsConfigPath}`); if (!__WEBPACK_EXTERNAL_MODULE_fs_extra__["default"].existsSync(tsConfigPath)) throw new Error(`tsconfig.json file does not exist, actual path:${tsConfigPath}`); }; const convertToModulePath = (path)=>{ if ('win32' === __WEBPACK_EXTERNAL_MODULE_os__["default"].platform()) return path.replaceAll('\\', '/'); return path; }; class TsPathsToRelativePathRspackPlugin { getTsConfigPath(compiler) { if (this.defaultTsConfigPath) return this.defaultTsConfigPath; const config = compiler.options.resolve.tsConfig; if (config) { if ('string' == typeof config) return config; return config.configFile; } return ''; } apply(compiler) { const tsConfigPath = this.getTsConfigPath(compiler); assertionTsConfigPath(tsConfigPath); const { compilerOptions = {} } = __WEBPACK_EXTERNAL_MODULE_fs_extra__["default"].readJsonSync(tsConfigPath, 'utf-8'); const { baseUrl, paths } = compilerOptions; compiler.hooks.normalModuleFactory.tap(this.pluginName, (normalModuleFactory)=>{ normalModuleFactory.hooks.beforeResolve.tapAsync(this.pluginName, (resolveData, callback)=>{ for(const p in paths){ const v = paths[p]; const alias = p.replace('*', ''); if (resolveData.request.startsWith(alias)) { const aliasPath = convertToModulePath(__WEBPACK_EXTERNAL_MODULE_path__["default"].join(baseUrl, v[0].replace('*', ''))); const fullAliasPath = convertToModulePath(`${__WEBPACK_EXTERNAL_MODULE_path__["default"].resolve(__WEBPACK_EXTERNAL_MODULE_path__["default"].dirname(tsConfigPath), aliasPath)}/`); const fullPath = resolveData.request.replace(alias, fullAliasPath); resolveData.request = convertToModulePath(`./${__WEBPACK_EXTERNAL_MODULE_path__["default"].relative(__WEBPACK_EXTERNAL_MODULE_path__["default"].dirname(resolveData.contextInfo.issuer), fullPath)}`); break; } } callback(); }); }); } constructor(tsConfigPath){ _define_property(this, "pluginName", 'tsPathsToRelativePathRspackPlugin'); _define_property(this, "defaultTsConfigPath", void 0); if (tsConfigPath) this.defaultTsConfigPath = tsConfigPath; } } export { TsPathsToRelativePathRspackPlugin };