Reputation: 991
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>
?
Upvotes: 0
Views: 1793
Reputation: 26878
I know that
require
is not on browsers, but why, is it nodejs specific? Doesimport { 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.
Upvotes: 1
Reputation: 40852
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:
Upvotes: 1