Repository navigation
Provide a way to add the '.js' file extension to the end of module specifiers #16577
Description
Activity
It's not just related to #13422, it's the same issue. But responses have been quite negatives, despite the fact I think it's a important issue, so hope your issue will be better received.
Reacted by Nicolas DUBIEN, Aleksandr Avtomonov, Alex Ivasyuv, ajeyaraj, Anthony Alayo, Tom Byrer, Tomáš Hübelbauer, Aapo Alasuutari, Salathiel Genese, Sajan and 23 morequantuminformation commented
on Jun 16, 2017 AuthorMore actionsWell, I hope its added, we were really looking forward to discussing my POC using this in my next TypeScript podcast, but looks like we will have to wait to use TypeScript with no build tools.
DanielRosenwasser commented
on Jun 17, 2017 MemberMore actionsAt the moment TypeScript doesn't rewrite paths. It's definitely annoying, but you can currently add the
.jsextension yourself.Reacted by xcatliu, Rob Palmer, Benjamin Lupton, Andy Fleming, Arthaey Angosii, Young Zhang, Nicholas Jamieson, Justin Fagnani, lake2 and David RodriguesReacted by Joe Pea, Rin Tepis, resynth1943, sam fortunato, Myst, Fernando Pasik, Jeroen Akkerman, Alexander Falzberger, Joachim Wester, Chance Snow and 34 moreReacted by Marin Rusu, Gustavo Farias, Lezsák Domonkos, Patrick Kunka, Daniel Gormly, Moritz Hedtke, K3n4, Ron Don Jon, RangerOri and Guilherme NogaraReacted by Jomar Antônio Cardoso, Clément P, mantou, Andrew Varga, Arthaey Angosii, Daniele Orlando, resynth1943, Etienne, Fernando Pasik, James Robb and 12 moreReacted by Whale Mo- addedSuggestionAn idea for TypeScriptAn idea for TypeScript
on Jun 17, 2017 - changed the title
[-]Add .js file extensions to import declarations output for use in Chrome 51 ES6 module imports[/-][+]Provide a way to add the '.js' file extension to the end of module specifiers[/+]on Jun 17, 2017 - addedNeeds ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.This issue needs a plan that clarifies the finer details of how it could be implemented.
on Jun 17, 2017 DanielRosenwasser commented
on Jun 17, 2017 MemberMore actionsquantuminformation commented
on Jun 17, 2017 AuthorMore actionsThanks for the tip, I'll write a shell/node script to do this.
Daniel Rosenwasser (@DanielRosenwasser) would it make sense to collect the native ES6 module issues under a label?
Also, to generalize this issue a bit, I don't think it's actually about adding a
.jsextension, but resolving the module specifier to an actual path, whatever the extension is.Reacted by Nikos, Aluan Haddad, Maxime Kjaer, Pauan, Michael Frischeisen-Köhler, Ben Lesh, Peter Burns, Jordan Last, fantaclaus, Keith Henry and 36 more- addedDomain: ES ModulesThe issue relates to import/export style module behaviorThe issue relates to import/export style module behavior
on Jun 18, 2017 quantuminformation commented
on Jun 19, 2017 AuthorMore actionsI've come across another issue which isn't really the domain of typescript but it's for my use case.
I'm not sure how to handle node_modules. Normally webpack bundles them into the code via the ts-loader but obviously, this is not understood by the browser:
import { KeyCodes } from 'vanilla-typescript;
https://github.com/quantumjs/vanilla-typescript/blob/master/events/KeyCodes.ts#L3Adding a js extension here is meaningless.
I guess there would have to be a path expansion by typescript or a url resolver running on the server.
I appreciate its a rather niche case, but I think it would be a way TS could shine early in this area. Maybe it could be a plugin to the tsc compiler?
quantuminformation commented
on Jun 22, 2017 AuthorMore actionsFor anyone coming to this and wants an interim solution I wrote a script to add a js file extension to import statements:
"use strict"; const FileHound = require('filehound'); const fs = require('fs'); const path = require('path'); const files = FileHound.create() .paths(__dirname + '/browserLoading') .discard('node_modules') .ext('js') .find(); files.then((filePaths) => { filePaths.forEach((filepath) => { fs.readFile(filepath, 'utf8', (err, data) => { if (!data.match(/import .* from/g)) { return } let newData = data.replace(/(import .* from\s+['"])(.*)(?=['"])/g, '$1$2.js') if (err) throw err; console.log(`writing to ${filepath}`) fs.writeFile(filepath, newData, function (err) { if (err) { throw err; } console.log('complete'); }); }) }) });
I might make this into a cli tool..
Reacted by Tobias Cudnik, Horacio Gonzalez, Rodrigo, Gabriel Brieva, Sid, Kristian Silli, croraf, Nick, Yufan Lou, Geert-Jan Zwiers and 6 moreReacted by Sid and Kristian SilliReacted by Chance Snow, Tyler Miller, Ron Don Jon and Emilio MartinezReacted by Kristian SilliReacted by Benjamin Vincentaluanhaddad commented
on Aug 9, 2017 ContributorMore actionsJustin Fagnani (@justinfagnani)'s comment hits the nail on the head.
Also, to generalize this issue a bit, I don't think it's actually about adding a .js extension, but resolving the module specifier to an actual path, whatever the extension is.
when you write
import { KeyCodes } from 'vanilla-typescript';
or for that matter
import { KeyCodes } from 'vanilla-javascript';
you are importing from an module specifier, it may or may not be a file but adding
.jsto the end in this case is not likely to result in a valid resolution.If you are writing a NodeJS application then the NodeJS Require algorithm will attempt various resolutions but it will likely not attempt to resolve it to
'vanilla-typescript.js'because it references an abstract name and will, by convention and by configuration, be resolved (perhaps over various attempts) to something like'../../../node_modules/vanilla_typescript/index.js'.Other environments, such as AMD have differences as to how they perform this resolution but one thing that all of these environments have in common is some notion of an abstracted module specifier.
I bring this up because the ES Module implementations shipping in various browsers implement something that is incomplete. If we consider even our simplest dependencies, and as soon as we broach the subject of transitive ones, it becomes clear that there will need to be a way to configure the doggone thing.
That may be far off, but as you are discovering, it is not realistic to write to this (politely) proof of concept implementation we have been given.
Furthermore, I do not see how TypeScript could possibly help here since the issue is environment specific.
Nikos (@quantuminformation) your program for adding
.jsto paths looks nice, lightweight, elegant even, but you are ultimately implementing your own module bundler. That is fun and interesting work but it demonstrates the deficiencies in the current implementations available in browsers. Even if you write in pure JavaScript, you still need something to compile and package your transitively imported dependencies.I am basically just ranting about the fact that the implementation of ES Modules that was released is tremendously far from adequate.
Again NodeJS, RequireJS AMD, Dojo AMD, Sea Package Manager, CommonJS, Browserify, Webpack, SystemJS, all have their own differing ways of doing things but they all provide abstract name resolution. They have to provide it because it is fundamental.
Thank you for reading my rant.
Reacted by Raphael Dhainaut, Arthur Ozga, Daniel Rosenwasser, Miguel Angelo, Horacio Gonzalez, Michael Stillwell, Anthony Alayo, Brian Kim, Lillem4n, Valentin Hăloiu and 9 moreReacted by Daniel Rosenwasser, Horacio Gonzalez, Samuel Souza Cabral and Kirill GroshkovReacted by Kirill Groshkov and Changdae ParkReacted by Brian Kim and Kirill GroshkovNot sure which version of TS added it, but imports such as '
./file.js'now work (even if the file is actually file.ts).
TypeScript resolves the file fine, and outputs the complete.jsimport to the target.
lit-htmluse it: https://github.com/PolymerLabs/lit-html/blob/master/src/lib/repeat.ts#L15Reacted by Mike Hogye, Miguel Angelo, David Zulaica, Étienne Miret, Tom, Matt A, Joeri Bakker, 柴树杉, Sergei Startsev, perspectivus1 and 18 moreReacted by Tanja, Paulius Sasnauskas and Conrad BuckReacted by Kuba Szostak, Tanja, Aerton Oliveira, Paulius Sasnauskas and Conrad Buck277 remaining items
Load more actionsYes, thanks you, and apologies, sort of.
After posting I discovered that if you add the ".js" extension to the typescript import statement,
the code will be generated correctly (will not change) and typescript itself also keeps working with debugging option.
.
It still seems strange to me that you have to refer to not-yet-existing *.js files from their corresponding *.ts fles,
but hey, it works :-).TypeScript transpiles to JS but then generates broken (modern) JS code.
?
It works fine
example.ts
import { Example } from './example.js';
compiles to
example.js
import { Example } from './example.js';
This same argument has been made before in this thread but it still doesn't make sense. You can not import something from a compiled file, especially one that hasn't been created yet. No other programming language allows that. Java doesn't allow you to
importsomething from a.classfile. C and C++ don't allow you to#includesomething from a.ofile.Reacted by Pauanexample.ts
import { Example } from './example.js';I'm writing in typescript; importing something from a local path in the same project that only contains typescript files. How does appending a .js to the import statement make sense to you? We're not writing any javascript and there's no javascript file in the folder being referenced?
The .js file being referenced doesn't exist; and won't exist until after it's been transpiled to js, and when that happens in many cases it'll be stored somewhere else. Source code shouldn't be referring to it's own build artifacts.
At the very least, if I'm going to reference importing from another typescript file by name, it should be:
import { Example } from './example.ts';I further agree with the complaint that I shouldn't have to put the extension at all; let me just refer to ./example, and the transpiler can find the relative .ts file. And the transpiler should be responsible for appending .js in the transpiled output,
We really shouldn't have to provide the ".js" in the .ts source code.
Reacted by Martin Kolárik, Herman, Artyom M., Bo Lingen, Jérôme, Pauan, Raúl Santos and osatonFor the record, I totally agree with Dave Barreto (@db984)
that this is a bug / design flaw that should be fixed asap.
But the workaround that works for me is importing *.js modules from the *.ts files,
even if they don't exists yet with a clean build.
FYI: I'm using latest: VSCode 1.52.1 and TypeScript 4.1.3, Edge 87.0.664.66.You can not import something from a compiled file, especially one that hasn't been created yet. No other programming language allows that. Java doesn't allow you to import something from a .class file.
No, that's exactly what Java does. Exactly.
import org.example.Example, means that the .class file is (or will be) located atorg/example/Example.classon the classpath. Whereas the file structure of .java sources doesn't matter in the least...every .java source file from every package could be in one directory; javac doesn't care. Imports refer to .class file structure.C and C++ don't allow you to #include something from a .o file.
Which makes sense because C/C++ includes are done as text preprocessing on the source files. Whole different approach, whole different ballgame. Forget knowing about compiled files,
gcc -Eand #include is a templating language isn't even aware what actual C is.
If you're requiring the "file to exist", you should also have a problem with the "non-existent file"
lodashinimport * as _ from 'lodash'
The answer is that
lodashisn't a file, it's a module specifier.TypeScript doesn't change module specifiers. You can use
lodash,lodash/index,/home/me/project/node_modules/lodash/index.js,https://example.org/js/index.js, etc. and TS respects your choice.TS doesn't know anything about JS file<->module specifier relationships. It just knows how to resolve TS types from module specifiers. TypeScript plays around with extensions (.js, .ts, .jsx, .tsx, .d.ts) and directories (
@types) and even uses selective parts of files (declare module 'lodash' {})If you import from
lodashorlodash/index.js, TypeScript will attempt the various extensions and directories in it's algorithm to find the types for that JS module. This is how it has always been, for every import ever.I further agree with the complaint that I shouldn't have to put the extension at all
Then use a module loader that works with extensionless module specifiers.
But if you're interested in a module loader (native ES modules) that requires the exact path of the JS modules, know that TypeScript in fact supports using the exact path of the JS module. (Said differently, TypeScript supports locating TS types using the exact path of the JS module.)
Reacted by James Bromwell, Junxiao Shi, Justin Fagnani and Ryan CavanaughYes, thanks you, and apologies, sort of.
After posting I discovered that if you add the ".js" extension to the typescript import statement,
the code will be generated correctly (will not change) and typescript itself also keeps working with debugging option.It still seems strange to me that you have to refer to not-yet-existing *.js files from their corresponding *.ts fles,
but hey, it works :-).FunctionPoint as an alternative option, you can use a compiler plugin to add the extension at compile time: https://github.com/Zoltu/typescript-transformer-append-js-extension
Reacted by Daniele OrlandoNo, that's exactly what Java does. Exactly.
No it's not and you know exactly what I meant 🙂
What Java allows us to do is to import source files, not compiled files. It may so happen that in the compiled Java bytecode it does reference a file ending in
.class(probably not but I don't recall how it works) - but that's the compiler's decision, not ours. This is the main point you're missing: it's not about what letters you type after a dot; it's about forcing us, developers, to do something that is inherently wrong, which is to do the compiler's work by referencing build artifacts. It's not our responsibility, nor should we touch this in any way.Dave Barreto (@db984)'s reply is spot on.
Reacted by PauanWhere Paul Draper (@pauldraper) writes:
If you're requiring the "file to exist", you should also have a problem with the "non-existent file" lodash in
import * as _ from 'lodash'
The answer is that lodash isn't a file, it's a module specifier.A bare module specifier is a completely separate case. Here we are clearly relying on the compiler/runtime and project configuration to help it find a module named "lodash". Perhaps the file being imported is in
./node_modules/lodash/index.jsor perhaps its somewhere else. But its pretty clear that all the source code says is that its in the "lodash" module.When I import from
'../../services\core\example'without any extension, to me at least, that looks like an import of a module namedexamplefrom a specific location. I'm telling it where to look for theexamplemodule, but still not giving it a filename. And that works, and is logically consistent, because that is the path to where the source code for the module namedexamplelives but I'm still relying on the compiler and runtime etc to figure out the file name to import. I'm just naming a module and saying where to look for it.But when I import from
'../../services/core/example.js'with the js extension, that now looks an awful lot like a specific file in the source tree, given explicitly by filename. Yes, there is source code for a module there namedexample, but its in a file calledexample.tsthat I expect will be transpiled toexample.jsin the output folder at some point, and that is an extremely clumsy solution; because nowhere in my source tree do I have anything calledexample.jsso it doesn't make a lot of sense to be referencing it.To argue that
'../../services/core/example.js'is also really a just a module specifier may be technically correct, but its un-intuitive because it's also clearly a file reference and it doesn't resolve the complaint that'../../services/core/example.js'doesn't actually exist.It seems far more logical to me that typescript should explicitly support typescript source code esm modules that are part of the project and allow you to reference
'../services/core/example.ts'with a ts extension, and when it transpiles the referenced ts file to a js module it can swap in the .js extension in the transpiled output. Then I'm referencing a file that exists in the source, and leaving it to transpiler to transform it to a suitable valid module reference in the output.And again, I would go even further and also allow you to leave the extension off entirely, and it will look for the module specified at that path, much as it does for commonJS modules, even though that's not in the javascript esm standard. It's doing a transpilation step anyway, so it can do the legwork of resolving the the module specifier to a file reference. I'm using typescript because it makes life easier after all.
I agree that in an ideal world, TypeScript could take total ownership of the import paths and remap them appropriately.
But
tscdoesn't always (often) have visibility into where the*.jsartifacts actually live - its resolution is looking for*.d.tsfiles in many cases, so any such rewriting would be spotty at best. Given the inconsistency, the next best thing is to just not touch it at all, which is the current behavior.Reacted by Ryan Cavanaughits resolution is looking for
*.d.tsa) This already deviates from javascript; so 'not touching it at all' is already not accurate.
b) It's been working fine for project relative imports in commonJS all this time, with very similar constraints so I'm really not sure why you think this is a significant challenge where support could only be "spotty at best".
As near as I can tell the only real change is that esm module resolution standard requires the explcit .js extension when referencing importing a js file from a relative location where as the commonJS standard specified that it would search filename.js then filename.json etc automatically in this case.
- addedDeclinedThe issue was declined as something which matches the TypeScript visionThe issue was declined as something which matches the TypeScript visionand removedNeeds ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.This issue needs a plan that clarifies the finer details of how it could be implemented.
on Jan 5, 2021 RyanCavanaugh commented
on Jan 5, 2021 MemberMore actionsWell I've read all 385 comments again now as part of a FAQ update and here are my main takeaways:
- We are not going to implement features, even under a commandline flag, that imply changing JS semantics by rewriting it during emit
.jsfile extensions are now allowed, which was not true when OP was written, so the issue as described has been fixed- We are 100% committed to not rewriting JavaScript code as part of non-downleveling compilation. This is how everything else in TS works; see also this comment in a related feature request, and this comment in a related feature request. We are not going to implement features, even under a commandline flag, that imply changing JS semantics by rewriting it during emit
- Everyone should read this comment from this thread as it accurately summarizes the rest of the discussion IMO
Experience on these sorts of threads has shown that discussion tends to just remain circular at this point, so I'm going to lock to avoid notification noise for commentors and repo watchers. We are not going to implement features, even under a commandline flag, that imply changing JS semantics by rewriting it during emit.
- locked as resolved and limited conversation to collaborators
on Jan 5, 2021
In order to use es6 modules in the browser, you need a .js file extension. However output doesn't add it.
In ts:
import { ModalBackground } from './ModalBackground';In ES2015 output:
import { ModalBackground } from './ModalBackground';Ideally I would like this to be output
import { ModalBackground } from './ModalBackground.js';That way I can use the output in Chrome 51
Related to #13422