Resolving compiled default exports with ES6 syntax - javascript

I have a module, say as follows:
const awesomeFn = () => ...
export default awesomeFn;
It is built into ES5 using babel, and when I created another ES6 module, I want the following syntax:
npm i awesomeFn
// ./index.js
import awesomeFn from 'awesomeFn';
awesomeFn();
But this throws. Logging awesomeFn gives me { default: _default [Function()] } (or something like that), hinting that I'd need to do something like
import awesomeFnPackage from 'awesomeFn';
const { default: awesomeFn } = awesomeFnPackage;
How can I form my exports so that I don't have to do the default destructuring? Should I avoid default exports altogether for this reason?
Somewhat strangely, this works if:
I use esm, like so node -r esm index.js but not if I use mjs as the file extension (with "type": "module" set), only js
It doesn't work with --experimental-modules, --experimental-specifier-resolution=node nor "type": "module" in package.json,
In every non-working case, the import value is { default: [Function: awesomeFn] }, only with esm is the value [Function: awesomeFn]
So I guess that's the solution right now; rely on an external package for expected behaviour, or use named exports, which do work as expected. What is going on with this?

Solution provided here, which is to destructure the default property as stated in the question, or add yet another dependency to intuitively use es6 imports.
I'll leave out the reasoning for why this choice was made by Babel to the reader to research for brevity. My conclusion is to use ES5 or not to use default exports. ES6 syntax is a mess in the context of import/exports as of writing, not only in the context of this question, but in the context of npm packaging, file extensions, flags, package.json properties, etc.

Hei, it looks like a problem with your setup. Default functions are named "default" when exported (ES5).
You can probably destructure directly in the import statement like this:
import { default as awesomeFn } from 'awesomeFn';
awesomeFn()

Related

100% ESM module world - what it mean?

While reading about tree shaking in webpack documentation, I came across this sentence:
In a 100% ESM module world, identifying side effects is straightforward. However, we aren't there just yet.
What do they mean by "100% ESM module" and how it is different from the current import and export that we already use today?
reference: https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free
The documentation you're reading is contrasting two types of scripts:
Scripts which expose everything they do through what they import and export
Scripts which do something in addition to importing and exporting (this could be seen as a "side effect")
Consider a big library, one that installs itself as a namespace on the global object to expose its functionality. Let's say that jQuery did this - that is, that it runs something like
const jQuery = (function() {
// lots and lots of code
})();
export default jQuery;
window.jQuery = jQuery;
This contains a side-effect: the line
window.jQuery = jQuery;
This means that other parts of your application could use window.jQuery without jQuery being specifically imported into that module. For example, you might have
// someModule.js
export const doStuff = () => {
window.jQuery('div').text('Hi!');
};
And this can work without the line
import jQuery from 'jQuery';
inside the module script, because jQuery is on the window. (For this to work, there needs to be at least one module somewhere that does import 'jQuery'; or something like that, so that jQuery's code that assigns itself to the window runs)
Because of the side-effect, Webpack will have a harder time with automatic tree-shaking - you'll have to explicitly note which modules depend on modules with side-effects.
In contrast, a module without dependency side-effects would be the someModule.js example above: all it does it export a function, without adding or changing functionality elsewhere.
So by "100% ESM module", Webpack is probably referring to scripts for which all modules' dependencies are explicit with import statements, instead of having to depend on side-effects (like a non-imported module assigning something to the window).
There are two popular module syntax nodejs use.
Commonjs: https://nodejs.org/dist/latest-v14.x/docs/api/modules.html
// exporting
module.exports.a = 1
// or, exports is an alias to module.exports, for all differences check out docs
exports.a = 1
// you can assign module.exports object as well, this sets what's exported
module.exports = {
b: 2
}
// a is not exported anymore
// importing default import, imports module.exports object
const a = require('./b')
// or via named import
const {c} = require('./b');
ES modules: https://nodejs.org/dist/latest-v14.x/docs/api/esm.html
// names export
export const a = 1;
// default export
export default const b = 2;
// importing via name
import {a} from './c'
// importing default export
import c from './b'
Commonjs and esm are still in use. So we are not in %100 esm world yet.

What is the equivalent of module.exports for ES6 Modules?

I have an existing package written in JavaScript that I'm trying to convert to TypeScript. My question is, what is the equivalent of module.exports for ES6 Modules?
For example if I have the following code:
module.exports = function () {
console.log("Hello World");
};
The only way I have found to do this in ES Modules is by doing something like the following.
const myFunc = function () {
console.log("Hello World");
};
export default myFunc;
// OR
export { myFunc };
Of course, this is not the same thing as module.exports = //....
Which leads to this problem. When I run this through TypeScript and get the outputted code, users of the package will either need to use an import defaultExport from "module-name"; statement (which isn't bad), or instead of being able to access it using require("module-name") they will have to use require("module-name").default (if they are using standard JS, not TypeScript). Which obviously is a breaking API change for standard JavaScript users.
Obviously, the goal here is to have no breaking API changes (and require no changes for customers code).
One more requirement to any solution. In other places in the package I need to be able to export a lot of different files as one object. So in the past I've been doing:
module.exports = {
"thing1": require("./a.js"),
"thing2": require("./b.js")
};
So I need to be able to export this as normal without requiring the user to do thing1.default. This one so far seems like the easier requirement since I'm exporting an object which ES Modules seems to handle really well. It's when you are exporting a singular (non-named) expression that it gets really tricky.
Is there a way to do this without having to make this a breaking change to the API?
The solution here is to use the TypeScript export = command. This allows you to use either require or import with the module.
export = function () {
console.log("Hello World");
};
import myModule from "./lib/myModule";
// OR
const myModule = require("./lib/myModule");
For more information the TypeScript documentation has a guide about Migrating from JavaScript, and specifically a section called Exporting from Modules.
Typescript recommends not to rewrite your code, but instead to configure it to allow js modules.
When we were working on converting a very large app from js to TS, we took the position of writing new code in TS, and slowly converting js into ts (but not spend a whole lot of time just converting).
We needed to enable few options in the tsconfig.json, such as :
{
...,
"compilerOptions" : {
...
"moduleResolution": "node",
"allowJs": true,
...
},
"include" [
"path/to/my/js",
]
}
you also need to update your webpack.config.js:
module.exports = {
// ... my settings
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
}
You might also have to declare require as a function (if you are getting errors such as require is undefined):
declare function require(path: string): any;
more info is available here :
https://www.typescriptlang.org/docs/handbook/migrating-from-javascript.html
Most accurate replacement for module.exports in typescript is export default
export default {
"thing1": require("./a.js"),
"thing2": require("./b.js")
}
then you can use them like below
import myThings from '.....'

Import JS web assembly into TypeScript

I'm trying to use wasm-clingo in my TypeScript React project. I tried to write my own d.ts file for the project:
// wasm-clingo.d.ts
declare module 'wasm-clingo' {
export const Module: any;
}
and import like this:
import { Module } from 'wasm-clingo';
but when I console.log(Module) it says undefined. What did I do wrong?
Notes:
clingo.js is the main js file.
index.html and index_amd.html are two example pages
Solution:
I solved the problem like this:
// wasm-clingo.d.ts
declare module 'wasm-clingo' {
const Clingo: (Module: any) => Promise<any>;
namespace Clingo {}
export = Clingo;
}
and
import * as Clingo from 'wasm-clingo';
Here's the source for this solution
I know you found a solution acceptable to you; however, you don't really have any types here, you just have Module declared as any, which gives you no typescript benefits at all. In a similar situation I used #types/emscripten, which provides full type definitions for web assembly modules compiled using emscripten. You simply need to do:
npm install --save-dev #types/emscripten
then change your tsconfig.json types array to add an entry for emscripten.
After that you can just write Module.ccall(...) etc. If you like you could of course write const Clingo = Module and then make calls against that if you want a more descriptive name than Module (which is a terrible name!).
You're welcome ;)
I think the issue is that wasm-clingo exports the module itself but import { Module } from 'wasm-clingo' expects a property.
Try
import Clingo_ from 'wasm-clingo';
const Clingo: typeof Clingo_ = (Clingo_ as any).default || Clingo_;

How do we declare import types from NPM library that has no declaration files?

For example, if I have the following in my app,
import Node from 'infamous/motor/Node'
console.log(Node)
that works just fine. But the moment I actually do something with it,
import Node from 'infamous/motor/Node'
console.log(new Node)
then TypeScript will complain because there's no type definition for Node. How do I define the type of Node?
The library has no type declarations of it's own. I tried something like
import MotorNode from 'infamous/motor/Node'
declare class MotorNode {}
console.log(' --- ', new MotorNode)
but I get the error
./src/app.tsx(6,8): error TS2440: Import declaration conflicts with local declaration of 'MotorNode'
When I need to do what you are trying to do, I create an externals.d.ts file in which I put module augmentations for my project and make sure that my tsconfig.json includes it in the compilation.
In your case the augmentation might look something like this:
declare module "infamous/motor/Node" {
class Node {
// Whatever you need here...
}
export default Node;
}
I put it in a separate file because a module augmentation like this has to be global (must be outside any module), and a file that contains a a top-level import or export is a module. (See this comment from a TypeScript contributor.)

Webstorm ES6 named import getting cannot resolve symbol error

I have an error in Webstorm when using ES6 named import declaration:
import { nodes } from 'utils/dom';
I get "cannot resolve symbol" error on "nodes"
Also when I try to export as named export like this:
export {
write: document.write.bind(document),
node: document.querySelector.bind(document),
nodes: document.querySelectorAll.bind(document)
};
I get errors too.
I use eslint with babel-eslint parser.
The thing is that this works in Sublime Text 3 as a charm, but for some reason fails error checking in Webstorm.
I assume that this is because except Eslint webstorm is doing other code checking.
Any Idea how I can suppress that and use only eslint with babel-eslint parser?
Any advice will be appreciated
I get "cannot resolve symbol" error on "nodes"
is because utils/dom in standard Node code means "find dom.js inside a module called 'utils'. You have overridden this behavior by using webpack's moduleDirectories property, but WebStorm doesn't know what that is. For WebStorm to properly resolve utils/dom, you'll need to add the utils folder as a library in your webstorm project configuration.
Your export syntax is incorrect. ES6 import/export syntax is 100% unrelated to objects, and in your example export, you are using object syntax. import { nodes } is asking for an export named nodes. There are multiple ways that you could write the exports that you have:
export const write = document.write.bind(document);
export const node = document.querySelector.bind(document);
export const nodes = document.querySelectorAll.bind(document);
or alternatively you could collapse them if you like multiline var/let/const
export const write = document.write.bind(document),
node = document.querySelector.bind(document),
nodes = document.querySelectorAll.bind(document);
or even
const write = document.write.bind(document);
const node = document.querySelector.bind(document);
const nodes = document.querySelectorAll.bind(document);
export {write, node, nodes};
Hard to say if this is directly related, but for Webstorm to know how to resolve your imports, you can also go to Preferences > Directories and set folders as Resource Root (or right/context-click on a folder and set it that way)
This might need to be done, for example, when you've configured Webpack to resolve certain sub-directories, where your project structure might be:
/
/docs
/src
/containers
/app
App.js
/components
/header
Header.js
In which case Webstorm would expect an import in App.js to look like the following:
import Header from '../../../components/header/Header'
Whereas with Webpack, if you've added src as a module to resolve, you can do the following, which Webstorm doesn't currently understand, hence adding it as a Resource Root resolves the issue
import Header from 'components/header/Header'
Reference: Path aliases for imports in Webstorm

Categories

Resources