The difference between "require (x)" and import x

I just started working on a small project node that will interact with MongoDB. However, I cannot get the appropriate node modules to import correctly, even if I installed them correctly through npm.

For example, the following code throws an error and reports that β€œexpress has no default export”:

import express from "express";

However, this code works:

const express = require("express");

So my question is: what is the difference in how the import and variable / require methods work? I would like to fix everything that interferes with my import in the project, as this may cause additional problems in the future.

+46
5
+43

require import , require node_modules , import, ES6, .

babel import export, import , require.

Node.js import (, ), , Node.js, import node_modules, ES6 .,

import babel, , node_modules, ?


, babel import ES6 CommonJS, require .

, app_es6.js :

import format from 'date-fns/format';

date-fns.

package.json - :

"scripts": {
    "start": "node app.js",
    "build-server-file": "babel app_es6.js --out-file app.js",
    "webpack": "webpack"
}

.babelrc .babelrc :

{
    "presets": [
        [
            "env",
            {
                "targets":
                {
                    "node": "current"
                }
            }
        ]
    ]
}

build-server-file package.json babel app_es6.js app.js

build-server-file, app.js date-fns, , :

var _format = require("date-fns/format");

var _format2 = _interopRequireDefault(_format);

- , .


: , , date-fns node_modules/date-fns/get_year/index.js , :

var parse = require('../parse/index.js')

function getYear (dirtyDate) {
  var date = parse(dirtyDate)
  var year = date.getFullYear()
  return year
}

module.exports = getYear

babel, app_es6.js :

import getYear from 'date-fns/get_year';

// Which year is 2 July 2014?
var result = getYear(new Date(2014, 6, 2))
//=> 2014

Babel :

var _get_year = require("date-fns/get_year");

var _get_year2 = _interopRequireDefault(_get_year);

.

+18

- require & import

-require

var express = require('express');

-import

import * as  express from 'express';

, "express". app :

var app = express(); 

'require' 'CommonJS' 'import' 'ES6'.

'require' & 'import', .

require - Node.js: ,

import - ES6 Node.js

+6

, , .

In node V10, you can use the flag --experimental-modulesto tell Nodejs what you want to use import. But your input script should end in .mjs.

Please note that this is still an experimental thing and should not be used in production.

// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
    print:function(){console.log('print called')}
}

Link 1 - Nodejs Document

Link 2 - github release

0
source

import is used in typewriting (angular). require is used in ES6 (ExpressJs)

0
source

All Articles