Search code examples
javascriptjquerysystemjscommonjs

why require need .js extension while importing js file


I am trying to implement CommonJS patten using below link

https://blog.risingstack.com/node-js-at-scale-module-system-commonjs-require/

I am getting error file not found error why ? here is my code https://plnkr.co/edit/mYeCYw9MOr87b4dQZr5I?p=preview Error is present on this line const add = require('./login')

when I added .js after login it works but In example it doesn't add .js extension why ? most of time i used require with js extension.

const add = require('./login')

console.log(add(4, 5))  

Solution

  • If you want to continue being able to omit the .js extension you can use the defaultExtension option in your SystemJS configuration. If I add this to your plunker, it loads without error:

    SystemJS.config({
      packages: {
        '': {
          defaultExtension: "js"
        }
      }
    })
    

    This defines a package that encompasses all your code and for which the default extension, if not specified in the module request, is .js.