Ts-loader never uses enhanced-resolve as of enhanced-resolve v5.3.1

未关闭
#1,492 7 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
38/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
停滞
技术栈
typescript, webpack

调研方向

从 src/servicesHost.ts 中的 resolveModule 开始,检查 enhanced-resolve resolver 的调用方式以及错误的处理方式。使用链接的最小仓库及其自定义 fileSystem 配置重现该问题。当 enhanced-resolve 接收到已配置的文件系统,并且模块解析不再静默绕过它时,即表示完成。

由索引模型根据 Issue 内容生成。

描述

When resolving modules attempts are first made to use enhanced-resolver (which is also used by webpack), and if that fails we fallback to the typescript resolver (src/servicesHost.ts:resolveModule ). In doing this undefined is passed as the context to the enhanced-resolver's resolveSync method.

Prior to version 5.3.1 the context value was not validated, as opposed to v5.3.1 onward (see https://github.com/webpack/enhanced-resolve/pull/261), of which the first check is to see if it's an object or not. This results in a error being throw, of which this is handled silently (see https://github.com/TypeStrong/ts-loader/blob/b4b036325b4cd97fab8b3f01fc7bc849373839d4/src/servicesHost.ts#L1270)

This means enhanced-resolve is never used, of which this is hard to pick up as we handle all error silently and fallback to the typescript resolver.

Expected Behaviour

To use enhanced-resolve when resolving modules.

Actual Behaviour

The enhanced resolver is never used when resolving modules, and falls back to the typescript resolver.

Steps to Reproduce the Problem

Try to use a custom fileSystem, by specifying this in your webpack's resolve options. Rather than this option being passed on to the enhanced-resolver , it is neglected, meaning that ts-loader falls back to the default/standard typescript filesystem. This is highlighted by the snippet code below (or in the example project below)

webpack.config.js

const fs = require("fs")
const path = require("path")
const memoryFS = require('memory-fs');
const unionfs = require("unionfs").ufs

var mfs = new memoryFS();
mfs.mkdirpSync(__dirname)
mfs.writeFileSync(path.join(__dirname,'fileSystemType.ts'), `export default () => {
  return "Using memory filesystem"
}`);

const updatedFs = unionfs.use(fs).use(mfs)

module.exports = {
  entry: "./index.ts",
  output: {
    filename: 'main.js'
  },
  target: "node",
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"],
    fileSystem: updatedFs
  },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: "ts-loader" }
    ]
  },
  plugins: [
    new class {
     apply(compiler){
       compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => {
         compiler.inputFileSystem = updatedFs
       });
     }
    }
 ]
};


index.ts

import filesystemType from "./fileSystemType";
console.log(filesystemType())

Expected Output (running npx webpack and node dist/main.js)
"Using memory fileSystem"

Actual Output (running npx webpack)
TS2307: Cannot find module './fileSystemType' or its corresponding type declarations.

Location of a Minimal Repository that Demonstrates the Issue.

https://github.com/walisc/ts-loader-enhance-resolver-bug

Proposed Fix

Passing an empty object as opposed to undefined, to resolveSync. In addition, it would be good to distinguish between configuration errors and actual resolve errors. In the snippet below I do this through a resolver plugin. Do note, this is just a poc, and maybe more work /cleaning up might be required.

diff -ur ts-loader-enhance-resolver-bug/node_modules/ts-loader/dist/resolver.js ts-loader/node_modules/ts-loader/dist/resolver.js
--- ts-loader-enhance-resolver-bug/node_modules/ts-loader/dist/resolver.js	2022-08-13 09:21:51.220999000 +0200
+++ ts-loader/node_modules/ts-loader/dist/resolver.js	2022-08-14 00:59:11.408463176 +0200
@@ -2,8 +2,27 @@
 Object.defineProperty(exports, "__esModule", { value: true });
 exports.makeResolver = void 0;
 const enhanced_resolve_1 = require("enhanced-resolve");
+
+ class ResolveStatusPlugin {
+    setResolveSync(resolveSync){
+        this.resolveSync = resolveSync
+    }
+    apply(resolver){
+        resolver
+            .getHook("noResolve")
+            .tap("resolveStatusPlugin", (obj, error) => {               
+                this.resolveSync["resolveStatus"] = "failed"
+            });
+    }
+}
 function makeResolver(options) {
-    return enhanced_resolve_1.create.sync(options.resolve);
+    const resolveStatusPlugin = new ResolveStatusPlugin()
+    options.resolve["plugins"] = "plugins" in options.resolve ? [...plugins, resolveStatusPlugin] : [resolveStatusPlugin]
+
+    const resolveSync = enhanced_resolve_1.create.sync(options.resolve);
+    resolveStatusPlugin.setResolveSync(resolveSync)
+    return resolveSync
+
 }
 exports.makeResolver = makeResolver;
 //# sourceMappingURL=resolver.js.map
\ No newline at end of file
diff -ur ts-loader-enhance-resolver-bug/node_modules/ts-loader/dist/servicesHost.js ts-loader/node_modules/ts-loader/dist/servicesHost.js
--- ts-loader-enhance-resolver-bug/node_modules/ts-loader/dist/servicesHost.js	2022-08-13 09:21:51.220999000 +0200
+++ ts-loader/node_modules/ts-loader/dist/servicesHost.js	2022-08-14 00:59:51.609128561 +0200
@@ -732,7 +732,7 @@
 function resolveModule(resolveSync, resolveModuleName, appendTsTsxSuffixesIfRequired, scriptRegex, moduleName, containingFile, redirectedReference) {
     let resolutionResult;
     try {
-        const originalFileName = resolveSync(undefined, path.normalize(path.dirname(containingFile)), moduleName);
+        const originalFileName = resolveSync({}, path.normalize(path.dirname(containingFile)), moduleName);
         if (originalFileName) {
             const resolvedFileName = appendTsTsxSuffixesIfRequired(originalFileName);
             if (resolvedFileName.match(scriptRegex) !== null) {
@@ -740,7 +740,11 @@
             }
         }
     }
-    catch (e) { }
+    catch (e) { 
+        if (resolveSync.resolveStatus != "failed"){
+            throw e
+        }
+    }
     const tsResolution = resolveModuleName(moduleName, containingFile, redirectedReference);
     if (tsResolution.resolvedModule !== undefined) {
         const resolvedFileName = path.normalize(tsResolution.resolvedModule.resolvedFileName);

主要语言
TypeScript
星标
3.5k
派生
439
平均合并
8 小时 6 分钟
30 天内合并 PR
12

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

  • 提供 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

TypeStrong/ts-loader 的其他 Issue

查看 TypeStrong/ts-loader 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。