Search code examples
javascriptnode.jsimportecmascript-6require

What's the equivalent of this import statement using require?


I'm trying to convert a few files from using import to using require to avoid the need for Babel.

One import statement is like this:

import React, { Component } from 'react';

How can I convert it to a require statement? I've tried with this:

const React, { Component } = require('react');

but it says there's an error at the first comma so it doesn't seem to be a valid syntax. Any idea?


Solution

  • Basically you will need to do the following:

    Either this syntax:

    const React = require('react');
    const { Component } = require('react').default;
    

    Or this syntax:

    const React = require('react');
    const Component = React.Component;
    

    For more details: https://github.com/babel/babel/issues/3049#issuecomment-286205548