Taylor Austin
Taylor Austin

Reputation: 6027

How to use import instead of require with node js?

Goal: To be able to use es6 import, export default, etc...

What I have done is include a .babelrc file in the root of my project which contains:

 {
   "presets": ["env", "react", "stage-0", "stage-1"],
   "plugins": ["transform-object-rest-spread"]
 }

I looked at the docs on babel and for node it said that all I would have to do is include the preset "env" which I do, but when I try to do an statement like:

import { data } from './data'

I get an unexpected token error on the import statement, so I assume I am not doing something correctly.

Upvotes: 0

Views: 3267

Answers (1)

Muhammad Adeel
Muhammad Adeel

Reputation: 2884

Typical webpack.config.js

module: {
    rules: [
        {
            test: /\.js$/,
            use: 'babel-loader',
            exclude: /node_modules/,
        },
        ...
    ]
}

I suggest you update .babelrc to the following.

{
    "presets": [
        [
          "env",
          {
            "modules": false,
            "loose": true
          }
        ],
        "react"
    ],
    "plugins": [
        "transform-object-rest-spread"
    ]
}

for more goodies decorators / function binding / class props etc,

{
    "presets": [
        [
          "env",
          {
            "modules": false,
            "loose": true
          }
        ],
        "react"
    ],
    "plugins": [
        "transform-object-rest-spread",
        "transform-function-bind",
        "transform-class-properties",
        "transform-decorators-legacy",
    ]
}

Upvotes: 1

Related Questions