0

I know that require is not on browsers, but why, is it nodejs specific? Does import { some-module } from 'some-module-location' in typescript/ES6 actually do the same?

Also, can import be used instead of embedding js file in a webpage using <script>?

TuaimiAA
  • 973
  • 6
  • 15
  • `require` is a CommonJS spec stopgap (at least from the node.js perspective) since there was no "real" way to do modular loading in browser based JavaScript before ES6. CommonJS, AMD, and jQueries plugin system (kind of) all tried to fill that role until ES6 came in and introduced `import`. – zero298 Oct 10 '17 at 14:49
  • Can you give a little more detail on what you mean by "Also, can import be used instead of embedding js file in a webpage using – zero298 Oct 10 '17 at 15:05

2 Answers2

1

In nodejs require is implemented in a similar way as is done with requirejs. It is not a language feature but an ordinary function.

If you switch into debugging mode in node.js you will see that each fill is wrapped into a function:

 (function( exports, require, module, __filename, __dirname) {
     // the original source of the file
 })

import on the other hand is part of the ES6 specs.

Internally node.js would do that same for import and require, just with another syntax. TypeScript or WebPack will transpile the import to their own internal syntax that is similar to the one above.

And the browser support of import can be seen here:

MDN: import

t.niese
  • 39,256
  • 9
  • 74
  • 101
1

I know that require is not on browsers, but why, is it nodejs specific? Does import { some-module } from 'some-module-location' in typescript/ES6 actually do the same?

You're right, require is not a native browser function. However, it is a part of the CommonJS specification but not unique to node.js. You see, before ES2015/ES6 there was no native way to do modular organization/loading of JavaScript. To address this, 2 main methodologies came about: CommonJS and Asynchronous Module Definition (AMD).

Both have a require "keyword" that loads a specified module into a context. However, each loads it in a different way. You can read a lot about the differences in different questions like: Difference between RequireJS and CommonJS. The main difference is that CommonJS is synchronous while AMD is asynchronous.

Different frameworks and libraries used different loaders. AMD is used by require.js, Dojo, and AngularJS (albeit not exactly to the spec). The most noted implementation of CommonJS the one by node.js.

str
  • 42,689
  • 17
  • 109
  • 127
zero298
  • 25,467
  • 10
  • 75
  • 100