require an es6 module into an es5 module - javascript

This is a strange issue, but I'm trying to require an es6 module into a section of my application that is using es5.
es6file.js
import moment from 'moment'
etc...
es5file.js
var config = require('../../../es6file')
etc...
and I keep getting an error of Unexpected token import
This, of course, makes sense. But I'm wondering if there is an easy way to allow myself to import this file without updating my entire application to handle imports instead of requires.

Related

Implications of doing `import * as React from 'react'` vs `import React, { useEffect } from 'react'` [duplicate]

I've noticed that React can be imported like this:
import * as React from 'react';
...or like this:
import React from 'react';
The first imports everything in the react module (see: Import an entire module's contents)
The second imports only the default module export (see: Importing defaults)
It seems like the two approaches are different and fundamentally incompatible.
Why do they both work?
Please reference the source code and explain the mechanism...I'm interested in understanding how this works.
Update
This is not a duplicate of What is the difference between import * as react from 'react' vs import react from 'react'
That question was answered with general ES6 module information.
I am asking about the mechanism that makes the react module work like this. It seems to be related to "hacky" export mechanism in the source here but it's not clear how that enables both importing the entire module and just the default export into React and having both of those approaches work with transpiling JSX, etc.
TL;DR
Indeed ES import statements import default and import * are not the same thing, the fact that they behave the same in this case is a combination of how React authors chose to publish the library and compatibility layers in TypeScript (using esModuleInterop) or Babel and your bundler to make them "just work". It probably shouldn't work according to ES6 spec, but today we are still working in an era where JS modules are a mess, so tools like Babel, TypeScript, Webpack, etc try to normalize behavior.
More details:
React is not an ES6 library. If you look at the source code you see this in index.js:
const React = require('./src/React');
// TODO: decide on the top-level export form.
// This is hacky but makes it work with both Rollup and Jest.
module.exports = React.default || React;
(Note the comment, even in React source code they struggle with ES6 default export compatibility.)
The module.exports = syntax is CommonJS (NodeJS). A browser would not understand this. This is why we use bundlers like Webpack, Rollup, or Parcel. They understand all kinds of module syntax and produce bundles that should work in the browser.
But even though React is not an ES library, both TypeScript and Babel let you import it as if it is (using import syntax, rather than require(), etc), but there are differences between CJS and ES that have to be resolved. One of them is the fact that export = can give you things that ES has no spec-compliant way to import, like a function or a class as the module. To work around these incompatibilities Babel has for awhile allowed you to import CJS modules as if they were exporting something by default, or import as a namespace. TypeScript for awhile didn't do this, but more recently added that as an option under esModuleInterop. So now both Babel and TypeScript can pretty consistently allow a CJS module to be imported using default or namespace ES imports.
With TypeScript it also depends on how the type-definitions for the library are actually defined. I won't get into that, but you can imagine situations where thanks to transpilers and bundlers a particular import works at runtime, but TypeScript doesn't compile without errors.
Another thing worth mentioning is that if you look at the built code for React there is a UMD module version as well as the CJS version. The UMD version includes some gnarly runtime code to try to make it work in any module environment, including the browser. It's mainly for use if you want to just include React at runtime (ie you don't use a bundler). Example.
Confusing? Yeah, I think so. :)
You most likely have "allowSyntheticDefaultImports": true, set in your tsconfig.json, which essentially shuts the compiler up about default imports it thinks are invalid. Typescript added esModuleInterop which does essentially what babel does for module loading.
This allows you to use ES6 default imports even when the source code you're importing doesn't export anything as default
Typescript is strict (follows the rules) when it comes to this, which is why they require you to import * as React from 'react'. Or requires you to tell it to allow synthetic default imports in its base config.
More On That Here

`require` or `import` CommonJS node modules using rollup

I am unsure whether I am supposed to use the require version or the import version.
It doesn't state that in the documentation and I found a statement in a Github issue that
Mixing import and require is definitely discouraged. The only way for Rollup to handle require statements is with rollup-plugin-commonjs, but that plugin will skip any files with import or export statements.
which could be interpreted as: "You need to still use require otherwise the common-js plugin will ignore your file and things will not work." or as "always use import everything else would constitute mixing". So that really confused me.
Context
I am trying to import a CommonJS library (Citation-js) into a javascript module (really typescript but I hope this is not relevant here). Now the documentation of common-js tells me to do
const Cite = require('common-js');
which tells me that it is a commonjs library (right?). Therefore I added
import commonjs from "rollup-plugin-commonjs";
import { nodeResolve } from "#rollup/plugin-node-resolve";
to my rollup config and put plugins: [commonjs(), typescript(), nodeResolve()] into the configuration.
Now vscode stops underlining everything and building the website with rollup works again. But the compiled javascript simply states require('common-js') and my browser complains that require is undefined.
Uncaught ReferenceError: require is not defined
So I tried
import Cite from 'common-js';
instead. But that resulted in the rollup build failing with
[!] Error: Unexpected token (Note that you need #rollup/plugin-json to import JSON files)
node_modules/#citation-js/core/package.json (2:8)
1: {
2: "name": "#citation-js/core",
^
Now I could of course install that plugin. But I am not sure that is right, since the whole point of a tool like rollup should be that dependencies of dependencies should be resolved automatically right?
I have also tried
Can't import npm modules in commonjs with rollup : "require is not defined"
This seemed like it would fix my problem: Using Older Require Module With Rollup
But:
the rollup-plugin-node-builtins is apparently not maintained (npm protested with security vulnerabilities and I found this: https://github.com/rollup/rollup/issues/2881). EDIT: There is a new package rollup-plugin-polyfill-node replacing that I guess.
resolve is no longer a member of #rollup/plugin-node-resolve so I assume that this has become nodeResolve which I am already using...
EDIT: installing #rollup/plugin-json actually lets me build the site again (with a bunch of warnings)
(!) Missing shims for Node.js built-ins (which is not fixed by the rollup-plugin-polyfill-node above)
(!) Missing global variable names
(!) Circular dependencies
(!) Unresolved dependencies
not sure what to do about these warnings

Bootstrap.js is not transpiled in time in sailsJS

I am writing my backend in sails js using es6/7 and I have defined a class that performs a background task.
Now from this StackOverflow post I have learned that background tasks should be initiated at config/bootstrap.js. So I put the following inside that file:
import BackgroundService from '../api/services/backgroundService.js';
module.exports.bootstrap = function(cb) {
backgroundService= new BackgroundService();
backgroundService.run();
cb();
};
Now I'm getting typicall transpiler erros like:
import BackgroundService from '../api/services/backgroundService.js';
^^^^^^
SyntaxError: Unexpected reserved word[...]
or, when I replace the import with require:
TypeError: Cannot call a class as a function
(referring to the instantiation of the BackgroundService class)
This indicates that the files are either not transpiled in time or at all.
I couldn't find a solution to this yet.
Any ideas?
not sure if your problem still exists, but it it does: nodejs currently doesn't support es6 import. You can either go the old way
const BackgroundService = require('../api/services/backgroundService.js');
or use babel. For sails I'd suggest sails babel
Note: depending on your app's globals configuration you don't need to import services at all. If you have globals activated you can just directly call backgroundService

How to use ES6 import with hyphen

I really don't know how to do this and not sure how to google either.
Right now I have this
let source = require('vinyl-source-stream');
I would like to change to be import but this doesn't work
import {'vinyl-source-stream' as source} from 'vinyl-source-stream';
If that module even supports the ES6 import/export system, then what you want is this:
import source from 'vinyl-source-stream';
Your version is attempting to import an exported value named vinyl-source-stream from the module; instead, you just want the module itself to be imported (into an object named source in this case).
If you want everything in the module imported, instead of just the default exports, use this instead:
import * as source from 'vinyl-source-stream';
But neither of those will work if the module isn't actually written to use the new system.
This library doesn't use the ES2015 module system. It doesn't export at all, so you can't import it or from it.
This library uses the CommonJS module pattern (as can be seen in the source) and is meant to be requireed.
You could import the library with:
import form 'vinyl-source-stream';
which will cause the code to be executed, but that will be useless in this case since nothing (useful) will happen - in fact, you'll probably get a runtime exception due to undefined module.

Can't find module 'hbs' with ES6 style import

I'm doing this in TypeScript, but tried it in vanilla JS as well with the same error. I've pulled down two modules: express and hbs. I'm trying to use the ES6 import syntax like this:
import * as http from 'http';
import * as express from 'express';
import hbs from 'hbs';
The last line gives me an error saying it can't find module hbs. I'm looking right at it... I can see it just fine. However when I replace the line with the older CommonJS syntax:
var hbs = require('hbs');
It works fine... what gives? Still on the learning curve with ES6...
Observation 1... as you have in your other exports, you should either import the whole module with an alias:
import * as hbs from 'hbs';
Or you can choose to import specific exports:
import {thing} from 'hbs';
Observation 2... is hbs a TypeScript module, or a JavaScript one? If it is a JavaScript one (as I believe it may be) you will need to pair it with a definition file, for example hbs.d.ts that describes the JavaScript file. TypeScript won't recognise a plain JavaScript module without the definition.
I was experiecing a similar problem. The syntax is correct ES6 indeed.
Good news is that the problem seems to have been fixed already in the development version of the typescript compiler 0.8: try 'npm install typescript#next -g' and then running the compiler again.
you should use default as the imported module name .
import {default as hbs} from "hbs";
this works same as
var hbs = require('hbs');
because require("hbs") imports default module exported by hbs.

Categories