Search code examples
javascriptecmascript-6commonjs

CommonJS alternative to ES6's importing as alias


ES6 can import an export as alias, like so;

import express from 'express'
import { express as playground } from 'graphql-playground/middleware'

Is there an alternative way to do this with CommonJS require('something')? Or something that circumvents the above declaration issue if it were done the CommonJS way?

This throws an error.

const express = require('express')
const express = require('graphql-playground/middleware')

// SyntaxError: Identifier 'express' has already been declared

Solution

  • CommonJS is really just assigning values to variables and you can name the variables however you want:

    const express = require('express');
    const playground = require('graphql-playground/middleware').express;