Skip to content

Suggestion: custom loaders for webpack integration.  #12828

Closed
@aj0strow

Description

@aj0strow

Please see my prior issue. (#11975)

Scenario

I have a pretty normal looking react project layout.

project/
├── node_modules
├── src
│   ├── modules
│   └── components
├── webpack.config.js
└── tsconfig.json

I have the following goals.

  • Import commonjs modules from /node_modules.
  • Don't import modules from $HOME/node_modules.
  • Import es6 modules from /src by name (not by relative path)
  • Import css modules and generate default typescript export on the fly.
  • Import react components with inline HTML in JSX syntax.
  • Import typings from /typings.
  • Import typings from /node_modules/@types.
  • Build project with webpack.

It's unclear how to accomplish my entire list. Webpack works great for JavaScript, but the issue is TypeScript can never find anything. I want static typing but it's too difficult to figure out. Instead, I end up with a hybrid code base.

Solution

See Jest transform for inspiration.

It would be nice if TypeScript allowed user defined resolution and file reading functions. I'd imagine the types could look like this:

resolveModule(absolutePath: string, moduleName: string): Promise<FileDescriptor>
readFile(absolutePath: string): Promise<NodeBuffer, SourceMap?>

I could provide nodejs modules that adhere to the interface.

{
    compilerOptions: {
        resolveModule: "./config/typescript/resolve.js",
        readFile: "./config/typescript/read.js",
    },
}

It would open up a world of possibilities for developers without needing constant changes to TypeScript core. The most popular strategies (like commonjs and typescript) could be bundled as a string constant instead of a path to code.

// tsconfig.json

{
    compilerOptions: {
        resolveModule: "commonjs",
        readFile: "typescript",
    },
}

If I want to do unusual things, like import image files as type string or parse CSS files for safe css module access, I should be allowed. The concept is similar to webpack loaders.

It's simple and configurable. It doesn't lock developers into using specific file extensions, or module resolution strategies, or frameworks, or build systems. TypeScript should just check types, and let developers provide modules and definitions as needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    SuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions