The major difference between require and import, is that import is native to JS, but require is only available in Node.js.
For reference, below is an example of how Babel can convert ES6's import syntax to CommonJS's require syntax. Do note that since Node.js v12, doing so is unnecessary.
Say the fileapp_es6.js contains this import:
import format from 'date-fns/format';
This is a directive to import the format function from the node package date-fns.
The related package.json file could contain something like this:
"scripts": {
"start": "node app.js",
"build-server-file": "babel app_es6.js --out-file app.js",
"webpack": "webpack"
}
The related .babelrc file could be something like this:
{
"presets": [
[
"env",
{
"targets":
{
"node": "current"
}
}
]
]
}
This build-server-file script defined in the package.json file is a directive for babel to parse the app_es6.js file and output the file app.js.
After running the build-server-file script, if you open app.js and look for the date-fns import, you will see it has been converted into this:
var _format = require("date-fns/format");
var _format2 = _interopRequireDefault(_format);
Most of that file is gobbledygook to most humans, however computers understand it.
Also for reference, as an example of how a module can be created and imported into your project, if you install date-fns and then open node_modules/date-fns/get_year/index.js you can see it contains:
var parse = require('../parse/index.js')
function getYear (dirtyDate) {
var date = parse(dirtyDate)
var year = date.getFullYear()
return year
}
module.exports = getYear
Using the babel process above, your app_es6.js file could then contain:
import getYear from 'date-fns/get_year';
// Which year is 2 July 2014?
var result = getYear(new Date(2014, 6, 2))
//=> 2014
And babel would convert the imports to:
var _get_year = require("date-fns/get_year");
var _get_year2 = _interopRequireDefault(_get_year);
And handle all references to the function accordingly.
expresswill be of typeany. You could include the definitions from here npmjs.com/package/@types/expressimport x = require('x')is not the same asvar x = require('x').