Currently, I am diving into Typescript to enhance my skills and knowledge. For a project that is being served with Flask and edited in VSCode, I am looking to convert the existing JavaScript code to Typescript. The main reason for this switch is to leverage the improved intellisense and type checking features available in VSCode when using Typescript.
After installing @types/jquery through npm, I encountered an issue where importing jQuery using import $ from "jquery"
in my .ts file did not throw any errors in VSCode. However, upon compiling the code with tsc and running it in Chrome, I faced a 'Failed to resolve module specifier "jquery"' error in the Chrome console. Interestingly, commenting out the import statement in the JavaScript code resolved the issue.
This situation leads me to wonder: How can one effectively utilize Typescript with an external library loaded from a CDN using a script tag without encountering import errors in the compiled Javascript code?
It feels like there should be a more efficient approach than manually modifying all the compiled code to remove imports for external libraries.
# This snippet appears identical in both the.ts and.js files,
# yet it triggers a 'Failed to resolve module specifier "jquery"'
# error when the .js file is executed within my project.
# Removing the import in the .ts file causes an error -Cannot find name '$'-
# during compilation.
# However, removing the import from the compiled .js file allows the page to load correctly.
import $ from "jquery"
function foo() {
$('#some-element')
}
<!-- jquery is loaded from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>