I am trying to import javascript packages from npm using JSPM module loader and use offline package loader instead of CDN.
now I want to add an importmap
script so I can import react
or another module in my module like:
import React from 'react'
what can I do to achieve this?

- 4,236
- 6
- 26
- 44
1 Answers
you can use importmap
as a standard new way to achieve your goal and import npm module in your js module file without writing a complete path like node_modules/react@16.x.x/index.js
and just write import React from 'react'
like previously we used to write in webpack or rollup.
to achieve that after you install jspm and install your needed package with jspm first run the following command:
jspm map -o importmap.json --flat-scope
it will generate a current importmap for jspm modules and then create a file that contains the importmap data. using --flat-scope is necessary because chrome currently dont support import maps scopes. you must fetch JSON file and inject it into your HTML file. first create a bootstrap.js
file and paste the following code in it:
class bootstrap{
constructor(){
this.initMapper().then(()=>{
this.lunchApp();
})
}
async initMapper() {
document.head.appendChild(Object.assign(document.createElement('script'), {
type: 'importmap',
innerHTML: await (await fetch('/importmap.json')).text()
}));
}
lunchApp(){
import('/Client/Assets/js/index.js');
}
}
var app = new bootstrap();
then add bootrstrap.js
into your index.html
file:
<script defer src="/Client/Assets/js/bootstrap.js"></script>

- 4,236
- 6
- 26
- 44