I’m new to typescript and I have a TS file wherein I needed to use $('#modal').modal('show')
from the bootstrap package. I am stuck now with this error
Uncaught SyntaxError: Cannot use import statement outside a module
after I compile my typescript.
I’m importing bootstrap in my TS file like this
import 'jquery';
import 'bootstrap';
import bootstrap from 'bootstrap';
// Some code here
const Modal = document.getElementById('modal') as HTMLElement;
const modal = new bootstrap.Modal(Modal);
modal.show();
// Some code here
Here is my package.json
{
"dependencies": {
"bootstrap": "^5.3.2",
"popper.js": "^1.16.1"
},
"devDependencies": {
"@types/bootstrap": "^5.2.10",
"@types/jquery": "^3.5.29"
}
}
and here is my tsconfig.json
{
"compilerOptions": {
/* Basic Options */
"target": "ES5",
"module": "ES6",
"lib": [
"ES2015",
"DOM"
],
"sourceMap": true,
"outDir": "./static/js",
"rootDir": "./static/ts",
"removeComments": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
/* Additional Checks */
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
},
}
I was hoping someone can guide me regarding this. I’ve been scouring the internet to resolve this and I know it’s a simple issue but it will be a great help if someone can explain me this.
Thank you.
To use bootstrap functions in my typescript
2
Answers
There are few changes to how to use bootstrap in typescript. Do follow step and I am sure it will work.
Install Bootstrap and its types definition:
Import Bootstrap and jQuery in your TypeScript file:
Use Bootstrap functionality:
Do let me know if need help or stuck.
jQuery dependency is not needed. Follow these steps
package.json
Add these
Please note to add
bootstrap.bundle.js
instead ofbootstrap.js
as the former includes Popper for positioning dropdowns, poppers, and tooltips.TS
Alternatively, you could just use Modal import like this