Error ts1192 module fs has no default export

I have tried importing fs module using import fs from 'fs' but this gives an error: `Module 'path' has no default export.'. import fs = require('fs'); works but this is ...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

astoilkov opened this issue

Jun 2, 2015

· 16 comments

Labels

By Design

Deprecated — use «Working as Intended» or «Design Limitation» instead

Comments

@astoilkov

I have tried importing fs module using import fs from 'fs' but this gives an error: `Module ‘path’ has no default export.’.

import fs = require('fs'); works but this is not ES6 syntax. I would like to stick with ES6 syntax because it is getting more and more popular and therefore easier to understand.

Are there any plans for supporting ES6 modules that import the entire TypeScript module?

@ivogabe

You should use

import * as fs from 'fs';

You can use your syntax if the module has a default export. Example:

// foo.ts
export default class Foo {
}

// bar.ts
import Foo from './foo';
new Foo();
christianrondeau, benvds, ManuelRauber, aegyed91, dheerajbhaskar, rickdgit, andyfleming, dev4201, tedwong, gitgrimbo, and 91 more reacted with thumbs up emoji
heracek, PendletonJones, and trisrael reacted with thumbs down emoji
k0pernikus, jestcastro, kazzkiq, ohcibi, liqiang372, cryptoquick, uhdang, aCodeAlchemist, ugreg, xmeng1, and 8 more reacted with hooray emoji
xmeng1, jackfischer, Pkmmte, jaimegomez, RobertoNovelo, jamonholmgren, JarLowrey, greybax, Jeremy-F, fbernardo, and 2 more reacted with heart emoji

@astoilkov

@tarruda

I suggest making the existing export = syntax compatible with export default. Right now it doesn’t seem possible to perform a default import of modules declared with the old syntax.

Take the tape module for example. I can’t import it using es6 syntax and the existing definition file. The following directive:

Fails with TS1192: External module ''tape'' has no default export.. If I change the definition file to use export default tape instead of export = tape then it works, but it will make the definition incompatible with typescript compilers < 1.5

raineorshine, oshalygin, Timopheym, muzuiget, ethanresnick, ErikSchierboom, cloutiertyler, TomasHubelbauer, Sayan751, aj0strow, and 36 more reacted with thumbs up emoji

@astoilkov

@danquirk

We talked a lot about whether we can (or should) make export= and export default the same thing. You can see the discussion and conclusions here: #2242 (comment)

@danquirk
danquirk

added
the

By Design

Deprecated — use «Working as Intended» or «Design Limitation» instead

label

Jun 8, 2015

This was referenced

Mar 29, 2016

@c9s

I used

import * as assign from "object-assign";

And the error message becomes:

error TS2497: Module ''object-assign'' resolves to a non-module entity and cannot be imported using this construct.

@c9s

Setting «target» to «es5» and

import fs = require('fs');
// or this
import assign = require('object-assign');

will work just fine, however this syntax will cause error with target = es6

@quantuminformation

What is wrong with:

import {Game} from "./Game";

game.ts:

export class Game {

I get the error:

error TS1192: Module '"lib/Game"' has no default export.

@mhegazy

game.ts does not have a default export. if it did, it would have looked like:

export default class Game {

@quantuminformation

@mhegazy I am not wanting to use a default export here.

@kitsonk

Is it Game.ts or game.ts… While some file systems allow case insensitivity in filenames, it can cause all sorts of strange issues in certain situations.

If it is Game.ts and the code is as you say it is, then it is unlikely that the error TS1192 actually refers to the code you are providing, as it should work and not generate the error your are encountering. It is likely something else is going on.

@mhegazy

can you share your code then. the error is only shown if you have a default import.

@quantuminformation

@quantuminformation

@mhegazy sorry please bear with me, I need to upload my local code after fixing smth.

@quantuminformation

imhoffd

added a commit
to ionic-team/legacy-ionic-cloud
that referenced
this issue

Sep 13, 2016

@imhoffd

@PendletonJones

—allowSyntheticDefaultImports solved this for me, #2242 #5577

jakearchibald, Alexisvt, kyasbal, Dr1Ku, jcrben, jgrosso, narkowicz, xcatliu, Riokai, AndrewBogdanovTSS, and 11 more reacted with thumbs up emoji
AndrewBogdanovTSS reacted with laugh emoji
narkowicz, AndrewBogdanovTSS, beauroberts, and soywod reacted with hooray emoji
AC4BB21B and BilledTrain380 reacted with heart emoji

@microsoft
microsoft

locked and limited conversation to collaborators

Jun 19, 2018

Labels

By Design

Deprecated — use «Working as Intended» or «Design Limitation» instead

SharePoint Online training courses

In this reactjs tutorial, we will discuss how to fix an error, error TS1192: Module has no default export. The solution will fix the below type of error:

  • error TS1192: Module has no default export
  • error TS1192 module has no default export
  • error ts1192 module ‘ http ‘ has no default export
  • error ts1192 module moment has no default export
  • error ts1192 module node_modules/moment/moment ‘ has no default export
  • error TS1192: Module ‘A.module’ has no default export
  • error TS1192: Module ‘ “D:/SPFx/CRUDReact1/node_modules/@types/react/index” ‘ has no default export.

The error comes while developing a SharePoint framework crud operations using react application. When I run the below command:

gulp build

It displays an error like below:

error TS1192: Module has no default export
error TS1192: Module has no default export

When I checked the code in the .tsx file, I saw the code like below:

import React, { Component } from 'react';
error ts1192 module moment has no default export
error ts1192 module moment has no default export

This line was creating the issue.

Then I have modified the code like below:

import * as React from 'react';

export default class CRUDReact extends React.Component<IHelloWorldProps, IStates> {

The other way, you can also modify the code like below:

import { React, Component } from 'react';

If you will write the above code, the error will not appear.

You may like the following tutorials:

  • React js form tutorial
  • What is react js and react native
  • Property welcome does not exist on type ‘JSX.IntrinsicElements’ in SPFx React
  • cannot find module jquery spfx
  • type ‘string’ is not assignable to type ‘number’.ts
  • Error TS2307 Cannot find module @pnp/sp/presets/all in SPFx
  • office-ui-fabric-react combobox example in SharePoint Framework

I hope this tutorial helps you to learn how to fix error, error TS1192: Module has no default export.

Bijay Kumar

I am Bijay a Microsoft MVP (8 times – My MVP Profile) in SharePoint and have more than 15 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com

To supplement @MikeC’s excellent answer, here are some relevant details from the current docs (v8.4.0) for writable.write():

If false is returned, further attempts to write data to the stream should stop until the 'drain' event is emitted.

While a stream is not draining, calls to write() will buffer chunk, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the 'drain' event will be emitted. It is recommended that once write() returns false, no more chunks be written until the 'drain' event is emitted. While calling write() on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required).

and for backpressuring in streams:

In any scenario where the data buffer has exceeded the highWaterMark or the write queue is currently busy, .write() will return false.

When a false value is returned, the backpressure system kicks in.

Once the data buffer is emptied, a .drain() event will be emitted and resume the incoming data flow.

Once the queue is finished, backpressure will allow data to be sent again. The space in memory that was being used will free itself up and prepare for the next batch of data.

               +-------------------+         +=================+
               |  Writable Stream  +--------->  .write(chunk)  |
               +-------------------+         +=======+=========+
                                                     |
                                  +------------------v---------+
   +-> if (!chunk)                |    Is this chunk too big?  |
   |     emit .end();             |    Is the queue busy?      |
   +-> else                       +-------+----------------+---+
   |     emit .write();                   |                |
   ^                                   +--v---+        +---v---+
   ^-----------------------------------<  No  |        |  Yes  |
                                       +------+        +---v---+
                                                           |
           emit .pause();          +=================+     |
           ^-----------------------+  return false;  <-----+---+
                                   +=================+         |
                                                               |
when queue is empty     +============+                         |
^-----------------------<  Buffering |                         |
|                       |============|                         |
+> emit .drain();       |  ^Buffer^  |                         |
+> emit .resume();      +------------+                         |
                        |  ^Buffer^  |                         |
                        +------------+   add chunk to queue    |
                        |            <---^---------------------<
                        +============+

Here are some visualisations (running the script with a V8 heap memory size of 512MB by using --max-old-space-size=512).

This visualisation shows the heap memory usage (red) and delta time (purple) for every 10,000 steps of i (the X axis shows i):

'use strict'

var fs = require('fs');
var wstream = fs.createWriteStream('myOutput.txt');
var latestTime = (new Date()).getTime();
var currentTime;

for (var i = 0; i < 10000000000; i++) {
    wstream.write(i+'n');
    if (i % 10000 === 0) {
        currentTime = (new Date()).getTime();
        console.log([  // Output CSV data for visualisation
            i,
            (currentTime - latestTime) / 5,
            process.memoryUsage().heapUsed / (1024 * 1024)
        ].join(','));
        latestTime = currentTime;
    }
}

console.log('End!')
wstream.end();

The script runs slower and slower as the memory usage approaches the maximum limit of 512MB, until it finally crashes when the limit is reached.


This visualisation uses v8.setFlagsFromString() with --trace_gc to show the current memory usage (red) and execution time (purple) of each garbage collection (the X axis shows total elapsed time in seconds):

'use strict'

var fs = require('fs');
var v8 = require('v8');
var wstream = fs.createWriteStream('myOutput.txt');

v8.setFlagsFromString('--trace_gc');

for (var i = 0; i < 10000000000; i++) {
    wstream.write(i+'n');
}

console.log('End!')
wstream.end();

Memory usage reaches 80% after about 4 seconds, and the garbage collector gives up trying to Scavenge and is forced to use Mark-sweep (more than 10 times slower) – see this article for more details.


For comparison, here are the same visualisations for @MikeC’s code which waits for drain when the write buffer becomes full:

The following articles tsconfug.json I removed the comment out, but I can’t get an error.

error TS1192: Module '"fs"' has no default export. I set tsconfig.json to take an error, but I noticed that the error was not loaded even if I set it.

I think that tsconfig is not loaded. Test "target": "es5", Home "target": "es6", changed but the variable definition varStay tsconfig.json I think it is not loaded.

npx tsc --target es6 index.ts js is output properly when runningconstContact

Comment npm install typescript --save-dev I don’t have a global install, so I need to specify the path as follows when compiling.

There is a folder where the compile method ts code is in, and on the hierarchy node_modules Contact
../node_modules/.bin/tsc index.ts
npx tsc index.ts However, was not read.

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true
  }
}

The code is like this.

import fs from 'fs'
// もう一つのこちらを使用するとエラーが取れる。
// import * as fs from 'fs'

処理

tsconfig.json

{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true,                         /* Enable incremental compilation */
"target": "es6",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [],                                   /* Specify library files to be included in the compilation. */
// "allowJs": true,                             /* Allow javascript files to be compiled. */
// "checkJs": true,                             /* Report errors in .js files. */
// "jsx": "preserve",                           /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true,                         /* Generates corresponding '.d.ts' file. */
// "declarationMap": true,                      /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true,                           /* Generates corresponding '.map' file. */
// "outFile": "./",                             /* Concatenate and emit output to single file. */
"outDir": "./test/",                              /* Redirect output structure to the directory. */
// "rootDir": "./",                             /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true,                           /* Enable project compilation */
// "tsBuildInfoFile": "./",                     /* Specify file to store incremental compilation information */
// "removeComments": true,                      /* Do not emit comments to output. */
// "noEmit": true,                              /* Do not emit outputs. */
// "importHelpers": true,                       /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true,                  /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true,                     /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true,                                 /* Enable all strict type-checking options. */
// "noImplicitAny": true,                       /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true,                    /* Enable strict null checks. */
// "strictFunctionTypes": true,                 /* Enable strict checking of function types. */
// "strictBindCallApply": true,                 /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true,        /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true,                      /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true,                        /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true,                      /* Report errors on unused locals. */
// "noUnusedParameters": true,                  /* Report errors on unused parameters. */
// "noImplicitReturns": true,                   /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true,          /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
// "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */

/* Module Resolution Options */
// "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./",                             /* Base directory to resolve non-absolute module names. */
// "paths": {},                                 /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [],                              /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [],                             /* List of folders to include type definitions from. */
// "types": [],                                 /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true,        /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true,                    /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true,                /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "",                            /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "",                               /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true,                     /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true,                       /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
// "experimentalDecorators": true,              /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true,               /* Enables experimental support for emitting type metadata for decorators. */

/* Advanced Options */
"skipLibCheck": true,                           /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */

}
}

I want to get an error in tsconfig setting. Thank you.

https://qiita.com/HorikawaTokiya/items/419d4f2d7a3ddaa606be

Editor’s note: This post was originally published in November 2018. Since then, Atomist has evolved and updated its platform and product offerings. For up-to-date information, check out the Atomist product page.

TypeScript has multiple syntaxes for imports. When should you use which?

It depends. 😞

Most of the time, the module exports multiple things

There are two great ways to import from another module when the module exports an object with properties. This is the common case.

Import the whole module, giving it a name:

import * as child_process from "child_process";

// then later...
child_process.spawn(...);

or pick the names you want to import:

import { spawn } from "child_process";

// then later
spawn(...);

Sometimes the module exports just one thing

This doesn’t work when the module doesn’t export an object with properties. Some modules export a function or a class instead.

How can you know? Good question. You have to look at the module’s code or look at examples.

Maybe it declares a default export for TypeScript

TypeScript has this concept of export default to declare the single thing that is exported. I wish it didn’t, because it makes this even more complicated.

If a module declares a default export, then you must bring it in like this:

import thing from "thing";

Now you have a function or a class (whatever its default export is) in thing.

Or more likely, it overrides the exports object with a single thing

More commonly in JavaScript (CommonJS?) modules, a module author will override module.exports to a function or class instead of adding properties to the exports object like a polite module would.

Look at the JS examples to find out what it is. For example, my favorite npm module boxen has this example, showing that what you get from it is a function:

const boxen = require('boxen');
 
console.log(boxen('unicorn', {padding: 1}));

In this case, how to import it depends on your compiler options. Try this style:

import * as boxen from "boxen";

Now this is confusing, because boxen here is not an object. It’s a function. You didn’t get all the things, you got the one thing.

BUT if in your compiler options you set "esModuleInterop": true, then TS will get clever and you can write this as:

import boxen from "boxen";

You only get one or the other style through your whole project. With esModuleInterop, TS sets up the default imports for you. But then importing with * does not work. You get to pick.

Or! How about a third way? This one works in either case, although it is not as pretty:

import thing = require("thing");

How do you know??

How are you supposed to know whether a module exports one thing or multiple? Maybe docs, or else look at the code.

Or, try both the «import * as blah» and the «import blah» syntaxes and see which works.

Sometimes you can look at examples and see how they use the export. These can be hard to translate from JS. For instance, in the npm page for boxen it shows:

const boxen = require('boxen');
 
// then later
boxen('unicorn', {padding: 1});

This shows that the thing it gets from requiring the module is being used as a function. So, it’s a single function. See above; syntax depends on your compiler options. Or use import boxen = require("boxen");.

In contrast, the npm page for chalk shows:

const chalk = require('chalk');
 
console.log(chalk.blue('Hello world!'));

Here, you can see that the thing it got from requiring boxen is being used as an object. Use import * as chalk from "chalk";.

How to know what a TypeScript module exports

A TypeScript module can say export default myFunction to export just one thing. Use import myFunction from "./myModule" to bring it in.

More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.

Do I have to name it after the module?

No, there’s nothing stopping you from naming your import whatever. You can import booger from "boxen" and then call booger("put this in a box"). This seems ridiculous. If this bothers you, tslint can yell at you for it: turn on the ‘import-name’ rule from tslint-microsoft-contrib.

When the module exports an object it is not so ridiculous. With lodash:

import * as _ from "lodash";

_.groupBy(...);

See, here the methods etc on the imported object all have the names assigned by the module author, so it doesn’t matter if I name the module object itself something cute. Please export an object, please.

Am I importing a module or a package?

If the import starts with «.» then it’s a relative import, and it’s a module. (A module is a file.) Otherwise, it’s conceptually a package, but really it’s the top-level module within the package. The top-level module is usually the package’s index.js, but that can be overridden in the main element of the package’spackage.json file.

Sometimes ‘import’ means ‘run’

You can import a script for side effects only:

import "./set_up_global_logging";

Fall back to JS

You can always const thing = require("Anything"); just like in JS, but you won’t get typing. You also won’t get compile-time checking that the module is available.

This will load the module dynamically, so you can conditionally load a module and then use it. This is handy when the module takes a long time to load, for instance.

Keep your TypeScript code clean and dependencies up to date using Atomist Skills.

How do you really feel, Jess?

Can we all just export an object, please? That way the properties have the name we give them instead of whatever name people assign them. I don’t like default exports. But some people do, and if I want to use their packages then I’ll deal with it. But I’m sad; I wish I could use import * as module from "module" all the time.

Appendix: Troubleshooting

Here are some error message translations.

No type declarations

Any of these imports can result in a compile error: error TS7016: Could not find a declaration file for module 'whatever-module'.

Here are your choices:

  • Ideal: try npm install --save-dev @types/whatever-module just in case someone has written type declarations for it. If this works, great.
  • Do this one: create a file called types.d.ts at the root of your source directory containing declare module "whatever-module"; . This counts as an explicit «any» declaration for the specific module.
  • Cheating: set "noImplicitAny": false in your compiler options in tsconfig.json. This makes TypeScript assume an «any» type for all modules. It also makes the compiler ignore when you forget to specify a type for each function parameter, so I don’t recommend it.
  • Less cheating: create a file called types.d.ts at the root of your source directory containing declare module "*"; . This counts as an explicit «any» declaration for every module.
  • Hard-core: create type declarations for the module you want to use, specific enough for the ways you use it. There’s a whole guide for this. It’s hard.

No default export

error TS1192: Module '"thing"' has no default export.

This means you tried to use import thing from "thing" but TS didn’t find a default export and you didn’t ask it to simulate them.

Here are your choices:

  • Use import * as thing from "thing"
  • Use import thing = require("thing");
  • Turn on esModuleInterop in tsconfig.json (caution: this might make other, existing imports behave differently)

Default is not populated

Here’s a runtime error: Uncaught TypeError: thing.default is not a function

In this case I’m using thing as a function, because I expected the module to export a function. But this is not from a TypeScript module, so it doesn’t use export default, nor from a module that tries to support TS, which would politely define exports.default.

One possible cause of this is: you used import thing from "thing" and it compiles because allowSyntheticDefaultImports is true in tsconfig.json. That option affects compilation only, and doesn’t create magic defaultiness in the emitted JS.

Either turn off allowSyntheticDefaultImports or turn on esModuleInterop. The latter does impact emitted JS.

A namespace-style import cannot be called or constructed

Here’s a compile error: error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof internal' has no compatible call signatures. Later it says: A namespace-style import cannot be called or constructed, and will cause a failure at runtime.

This one happens when I have import * as thing from "thing"; , I’ve turned esModuleInterop on in tsconfig.json, and the imported module exports one thing that is not an object.

Choices:

  • use import thing from "thing"
  • use import thing = require("thing")
  • Turn off esModuleInterop

I’ve never liked import thing = require("thing") because it looks like JavaScript instead of like a typed language. But it seems to work more consistently.

Editor’s note: This post was originally published in November 2018. Since then, Atomist has evolved and updated its platform and product offerings. For up-to-date information, check out the Atomist product page.

Понравилась статья? Поделить с друзьями:
  • Error trying to parse settings sublime text 3
  • Error trying to open unclosed connection
  • Error trying to find the directory for the game config file nfs hot pursuit
  • Error true undeclared first use in this function
  • Error truck data is missing trying to use a fallback truck