镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Handling input file extensions other than .ts, .js, .tsx, and .jsx #10939

Description

There has been multiple requests/issues for a more flexible use of file extensions. There are a few requests, but to summarize, they fall into one of the following two buckets:

Scenarios:

Today the file extensions are used in multiple places:

  • Discovering files from tsconfig.json
  • Module resolution
  • JSX syntax parsing
  • Use of specific features (e.g. type annotations in .js files)
  • Error reporting (e.g. no semantic errors for .js files)
  • The generated output file extension

Proposal:

Add a new compiler option extensions that would be a map from a file extension to a ScriptKind entry. If provided, the extension map would override the mapping of the extension.

Different parts of the compiler will need to ask for ScriptKind and not an extension (many already do, e.g. parsing). For tsconfig.json file discovery, the set of keys in extension map would be combined with the set of known extensions.

allowJs in this model would be an alias for "extensions": { ".js" : "JS" }. defining both properties would be an error.

Declaration files are the only exemption of this rule. A .d.ts file meaning can not be changed, and a declaration file can only have .d.ts extension.

{
    "compilerOptions": {
        "extensions" : {
             ".ts": "TS",
             ".es": "JS",
             ".js": "JSX"
        }
    }
}

Activity

  1. niieani commented on Sep 15, 2016

    @niieani

    That sounds like a good proposal, however there's one problem I see with scoping of these changes. If we set to treat all .js files as TS (for example), and the project mixes un-typed JS (or if you want to gradually type parts of it), it's going to generate errors.

    Perhaps instead of assigning "extensions", we could assign glob patterns?

    Example:

    {
        "compilerOptions": {
            "extensions" : {
                 "**/*.ts": "TS",
                 "**/*.es": "JS",
                 "src/**/*.js": "TS" // treat all JS files inside src as TS
            }
        }
    }
  2. RyanCavanaugh commented on Sep 16, 2016

    @RyanCavanaugh
    Member

    That's a really good idea -- it would solve the "Treat .js as JSX" problem for React Native at the same time

  3. added
    Too ComplexAn issue which adding support for may be too complex for the value it adds
    and removed on Sep 28, 2016
  4. RyanCavanaugh commented on Sep 28, 2016

    @RyanCavanaugh
    Member

    Declining in favor of #11158 -- the complexity of determining the grammar, emit extension, etc, especially in a loose file context, doesn't seem to outweigh the benefits relative to simply renaming the input files.

  5. niieani commented on Sep 28, 2016

    @niieani

    Ryan Cavanaugh (@RyanCavanaugh) really?
    This solves so much more use cases than just allowing .jsx. I'm really disappointed. 😞
    See all the relevant related issues, such as #9839, #9551, #7926, #7699 and #9670, listed by Mohamed Hegazy (@mhegazy).

    Even saying it won't be implemented until TypeScript 3.0 would be better than closing it. :(

  6. jbutz commented on Sep 28, 2016

    @jbutz

    Bazyli Brzóska (@niieani), I agree with you. I am very disappointed by this. I've been having issues with the first scenario Mohamed Hegazy (@mhegazy) listed since the release of VSCode and I have been looking for this feature ever since.

  7. mhegazy commented on Sep 29, 2016

    @mhegazy
    ContributorAuthor

    The rational here is what is the use of extensions if they do not mean what they say. a file with type annotations is not .js, and so is a file with JSX syntax. saying that they are is just an outright lie.

    For users who feel that .js is more community-friendly than .ts, we felt that this is doing community members a disservice. if the file is meat to contain typescript syntax, and meant to be processed by the typescript compiler, then why not advertise it. it will takes your community members 5 more seconds to know that the file is not really pure JS, so save them the trouble and call it a .ts.

    For users who want to use other extensions than .ts. We are open for changing the output extension, since that might be used by other tools down stream. an example for this is the react native case in #11158. If there are similar cases we would be happy to support them as well.

    As for tooling, tsserver does support loading files in different modes already. we can add additional server configuration to mark certain extensions, e.g. es or es6 as JS. but do not think support .js as TS or .ts as JS would be needed in these scenarios.

    This really comes down to Occam's razor. the simplest solution for tools and for users is for extensions to really mean what they are meant to mean. changing this only leads to complexity in the tooling and confusion to users.

  8. jonaskello commented on Sep 29, 2016

    @jonaskello

    Not sure #11158 would help in the jspm work-flow scenario? If I load and transpile files in the browser, they are loaded with their original extension (.ts, .tsx). If I want to use JSX in one file out of 100 in a package I will have to name all 100 files .tsx since JSPM has a single default extension per package. I would rather name all files .ts since 99 files does not contain any JSX. Another way to do it would be specify the extension in the imports and not having a default extension but AFAIK tsc does not allow that either.

  9. mhegazy commented on Sep 29, 2016

    @mhegazy
    ContributorAuthor

    Output file extension should be allowed in imports. See #4595

  10. jonaskello commented on Oct 9, 2016

    @jonaskello

    I was actually referring to input extensions, such as import foo from './bar.ts'. From what I gather that will give a compile error in 2.0.3, and this is a good thing. However, that means that we in SystemJS must use the defaultExtension option. So we have to choose one extension to use. So if we in a package have one typescript file with JSX and 100 without JSX, they all have to have the extension TSX. I think this is rather unfortunate. I would rather have all files with extension TS weather they contain JSX or not. For some more background see for example this issue and this issue.

  11. 24 remaining items

  12. ctsstc commented on Jun 18, 2018

    @ctsstc

    2018 and still we're nowhere with this :( 😞

  13. tunnckoCore commented on Jul 30, 2018

    @tunnckoCore

    Yea.. And even with 3.0 ...

    ❯ yarn build
    yarn run v1.7.0
    $ tsc --emitDeclarationOnly && babel src -d dist
    src/index.js:2:5 - error TS8009: 'private' can only be used in a .ts file.
    
    2     private x = 10
          ~~~~~~~
    
    src/index.js:4:21 - error TS8010: 'types' can only be used in a .ts file.
    
    4     setX = (newVal: number) => { this.x = newVal; }
                          ~~~~~~
    
    error Command failed with exit code 1.
  14. massimonewsuk commented on Jul 31, 2018

    @massimonewsuk

    I made a comment earlier on this thread (which I deleted) saying how I was using the TypeScript compiler to check Flow code (cause the TypeScript tooling is so much better), and how I wished we could allow the checking of JS code with type annotations.

    I have to say my use case is completely useless because Flow syntax is different in some cases anyway.

    Also, I'm thinking if TypeScript allowed people to specify any file extension then you'd get all these insane people in the JavaScript community who would input *.js files and be like "yeah I only write standards compliant JS, I only use TS for type checking", but their code is littered with non-standard type annotations (cough Flow users cough).

    I think it's fantastic that TypeScript type annotations are only allowed inside *.ts, *.tsx and and *.d.ts files and I think it should always be kept that way. It makes it much better for the community. Everyone knows immediately whether they are looking at a TypeScript file, or a standard JavaScript file. GitHub statistics are correct too (has anyone ever spotted metrics on how many people are using Flow? No... because they use the same *.js extension).

    Also people won't try doing node myFile.js and have it blow up due to syntax errors because they had non-standard type annotations (ahem, Flow). Imagine some poor kid trying to learn javascript sees a *.js file with all these type annotations inside and is like what? Why doesn't this run?

    I could go on and on about the list of reasons why it would be a terrible idea for TypeScript team to support custom extensions...

  15. mikepatrick commented on Aug 1, 2018

    @mikepatrick

    I don't have strong feelings on this issue, but I do have two cents to register.

    I think that eliminating file extension restrictions would open up options for people building their own tooling around tsc. That, in and of itself, may or may not be a good enough reason to consider it seriously. At any rate, consider this webpack example:

    This person wanted to create a webpack loader that would generate Typescript interfaces from files with (potentially) arbitrary extensions. These interfaces could then be passed along to the Typescript loader of choice.

    This was (arguably) more difficult/confusing than it could have been, due to a combination of the file extension restrictions and a poor error message.

    While ts-loader has a convenient work-around for this restriction (as documented in the link above), it's not great being tied to one particular loader (or having to write your own).

    Again, just two cents. I've been using TS full time for about a year, and I love it. Keep up the good work!

  16. duzenko commented on May 10, 2019

    @duzenko

    Sorry if I'm duplicating someone else but not being able to move forward with simple things like this is rather frustrating

  17. lellimecnar commented on Jun 3, 2019

    @lellimecnar

    With @babel/preset-typescript now being a thing, this needs to be allowed...

    We are using Babel for a rather large application, and we would like to slowly add types and use the new Babel preset. We are not interested in fully "switching" to the TypeScript ecosystem, and we are currently using non-TypeScript features via Babel plugins. It makes absolutely zero sense to rename all of our JS files to .ts just to silence the mountain of "'types' can only be used in a .ts file." messages in VS Code... and we can't move forward without a way of silencing those errors, since every single type annotation will be marked as an error, and the other devs will end up just ignoring everything...

    ...assuming that there is no valid use-case for something that developers keep asking for is never a good thing...

  18. gugadev commented on Jun 27, 2019

    @gugadev

    Really, there is no logic reason to do not implement this proposal. This is a must for god's sake.

  19. omeid commented on Jun 28, 2019

    @omeid

    Despite a few short comings, I have decided to stay with flowtype for the prime reason that it allows incremental use unlike TypeScript which has been hardheaded on this issue. I suggest you consider it for your project too, Lance Miller (@lellimecnar).

  20. JounQin commented on Jul 24, 2019

    @JounQin

    Any hack way??? Something like appendTsPrefixTo?

  21. bgraceful commented on Aug 1, 2019

    @bgraceful

    noun:I verb:am verb:guessing adjective:that noun:there auxiliary verb:is adjective:no noun:way preposition:to verb:run noun:typescript preposition:on indefinite article:a noun:String?

  22. strokirk commented on Aug 21, 2019

    @strokirk

    Ryan Cavanaugh (@RyanCavanaugh) can this issue please be re-opened, since there has been a lot of really thoughtful comments since the close date regarding the utility of this (simple) functionality?

    Or would it be better to open a new issue?

  23. jfrank14 commented on Oct 20, 2020

    @jfrank14

    My scenario is to be able to port a large Adobe Animate application from javascript to typescript. Animate uses a naming convention that I probably can't change. Logic for components is stored in files called MyComponent.js and MyComponent.jsfl, where the js file is generated code containing resources and the jsfl file is the code that you write to control the component.

    I DO actually want the source file to be Typescript, but I can't use a ts extension because each component has TWO source files and also two different output file extensions.

  24. Rigidity commented on Feb 6, 2021

    @Rigidity
  25. josh-sachs-epic commented on Oct 11, 2021

    @josh-sachs-epic

    I came across this proposal while trying to setup nextjs (react) to import css modules without requiring the '.css' extension.

    This currently works at runtime, but tsc reports it as an error ts(2307)

    tsconfig.json

     baseUrl": "./src",
     "paths": {
        "@api/*": ["pages/api/*"],
        "@pages/*": ["pages/*"],
        "@styles/*": ["styles/*.css"],
     } 
    

    When I import the module at src/styles/home.module.css as such:
    import styles from @styles/home.module

    it works at compile/runtime, but tsc validation in vscode keeps it flagged as an error.

    Doing something like:
    import styles from @styles/home.module.css validates fine (as long as I remove .css from the path delaration)

    Seems to me like using paths to extend typescript's base list of source file extensions should be a no brainer... and is 95% working today.

  26. RobertAKARobin commented on Dec 12, 2022

    @RobertAKARobin

    I have a situation where I want to import modules from a cache, in which all files have had their extensions removed. But I can't import them because of this limitation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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