How do you can use Import/Exports in your Node.js App

How do you can use Import/Exports in your Node.js App

Today's I'll share a short article about how you can use Import/Export statements in your node.js app, why? because in my case I have a React App that whit SSR features, then I need to share code between the client app and the server.

TL;DR

Problem:

what happens if you could use an import in your node.js app? let's do it:

import _ from 'lodash/get'


const result = _.get({ a: { b: 1 }}, 'a.b')

console.info(result)

and we got an error:

import _ from 'lodash'
^^^^^^                                                                     

SyntaxError: Cannot use import statement outside a module

Solution 1:

The same node gives us an advice:

Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension

This is ok, you only need to add the type: module into package.json:

"author": "", 
"type": "module", // <- Add this
"license": "ISC",

And works, but... your node app doesn't work with require/exports

const _ = require('lodash')

ReferenceError: require is not defined

Solution 2:

We'll use babel, Babel that is a (Javascript compiler)

npm install @babel/core @babel/preset-env @babel/register -save-dev

We need to create a babel.config.json, to use the preset-env

{
  "presets": ["@babel/preset-env"]
}

what is preset-env?

@babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!

and we need to create a new file to be the entry point instead of our current in my case is (index.js), I'll create a 'start.js'

require('@babel/register')({
  ignore: [/(node_modules)/]
})


require('./index');

in the start.js we are calling the babel process:

@babel/register: One of the ways you can use Babel is through the require hook. The require hook will bind itself to node's require and automatically compile files on the fly.

and after we load the old entry point (index.js)

import _ from 'lodash'


console.info(_.get({ a: { b: 1 }}, 'a.b'))

And it's all!! now we are using import/export the result when I run 'node index.js' is 1

Bonus:

Indeed we can use both ways look at this:

import _ from 'lodash'

const chalk = require('chalk')



console.info(_.get({ a: { b: 1 }}, 'a.b'))

console.log(chalk.blue('Hello world!'))

and the result of `node start.js`:

No hay texto alternativo para esta imagen

Enjoy!!


要查看或添加评论,请登录

Nicoandres Rodriguez的更多文章

社区洞察

其他会员也浏览了