简体   繁体   中英

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

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;

For non-default exports (module.export = var) you can also alias with regular destructure syntax:

const {
  originName: newNameInFile
} = require('foo.js')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM