module export in ts file is not a module error - javascript

I have a config.ts and I do
module.exports = { something: 123 }
when I import like import { something } from './config.ts' I got error of config.ts' is not a module, what's the issue? my typescript is configured rightly and it's working in other places.

If you're using import { something } from './config.ts', you're using JavaScript modules, but your code in config.ts is using CommonJS modules. Some bundlers and such may let you mix them, but it's best not to.
To make config.ts a JavaScript module compatible with that import declaration (which expects a named export called something), change it to:
export const something = 123;
Or, of course, to use config.ts via CommonJS, your code using it would be:
const { something } = require("./config.ts");
...but given the error you're getting, I think your project is set up to use JavaScript modules (import/export), which here in almost 2021 is probably best (now that we have dynamic import to handle the cases where static modules don't quite do the job).

Related

How to Convert, in JS, an import statement to a require() statement

I have a Statement in JavaScript:
import app, { set } from '../app';
How can I write an equivalent statement in a form, such as I don't get an error like 'Cannot use import statement outside a module'.
I could convert similar less complex statement by using a format:
var Foo = require(foo);
but don't understand how to convert this one.
Not every import can be converted into a require. In pure Node.js this is only possible if the module being required is a CommonJS module, but the situation is different with tools such as Webpack or Babel.
I image you are using one of those tools, otherwise you would not be able to import ../app without a file extension in the first place: you would need to import from ../app.js or ../app/index.js explicitly, or to use export mappings, but that's a different story.
Then if
import app, { set } from '../app';
is a valid import in a ES module, with whatever loader, the equivalent CommonJS syntax would be
const app = require('../app');
const { set } = app;

Conditional Import of 2 objets with the same name [duplicate]

I need to do something like:
if (condition) {
import something from 'something';
}
// ...
if (something) {
something.doStuff();
}
The above code does not compile; it throws SyntaxError: ... 'import' and 'export' may only appear at the top level.
I tried using System.import as shown here, but I don't know where System comes from. Is it an ES6 proposal that didn't end up being accepted? The link to "programmatic API" from that article dumps me to a deprecated docs page.
We do have dynamic imports proposal now with ECMA. This is in stage 3. This is also available as babel-preset.
Following is way to do conditional rendering as per your case.
if (condition) {
import('something')
.then((something) => {
console.log(something.something);
});
}
This basically returns a promise. Resolution of promise is expected to have the module. The proposal also have other features like multiple dynamic imports, default imports, js file import etc. You can find more information about dynamic imports here.
If you'd like, you could use require. This is a way to have a conditional require statement.
let something = null;
let other = null;
if (condition) {
something = require('something');
other = require('something').other;
}
if (something && other) {
something.doStuff();
other.doOtherStuff();
}
You can't import conditionally, but you can do the opposite: export something conditionally. It depends on your use case, so this work around might not be for you.
You can do:
api.js
import mockAPI from './mockAPI'
import realAPI from './realAPI'
const exportedAPI = shouldUseMock ? mockAPI : realAPI
export default exportedAPI
apiConsumer.js
import API from './api'
...
I use that to mock analytics libs like mixpanel, etc... because I can't have multiple builds or our frontend currently. Not the most elegant, but works. I just have a few 'if' here and there depending on the environment because in the case of mixpanel, it needs initialization.
2020 Update
You can now call the import keyword as a function (i.e. import()) to load a module at runtime. It returns a Promise that resolves to an object with the module exports.
Example:
const mymodule = await import('modulename');
const foo = mymodule.default; // Default export
const bar = mymodule.bar; // Named export
or:
import('modulename')
.then(mymodule => {
const foo = mymodule.default; // Default export
const bar = mymodule.bar; // Named export
});
See Dynamic Imports on MDN
Looks like the answer is that, as of now, you can't.
http://exploringjs.com/es6/ch_modules.html#sec_module-loader-api
I think the intent is to enable static analysis as much as possible, and conditionally imported modules break that. Also worth mentioning -- I'm using Babel, and I'm guessing that System is not supported by Babel because the module loader API didn't become an ES6 standard.
Import and Export Conditionally in JS
const value = (
await import(`${condtion ? `./file1.js` : `./file2.js`}`)
).default
export default value
Important difference if you use dynamic import Webpack mode eager:
if (normalCondition) {
// this will be included to bundle, whether you use it or not
import(...);
}
if (process.env.SOMETHING === 'true') {
// this will not be included to bundle, if SOMETHING is not 'true'
import(...);
}
require() is a way to import some module on the run time and it equally qualifies for static analysis like import if used with string literal paths. This is required by bundler to pick dependencies for the bundle.
const defaultOne = require('path/to/component').default;
const NamedOne = require('path/to/component').theName;
For dynamic module resolution with complete static analysis support, first index modules in an indexer(index.js) and import indexer in host module.
// index.js
export { default as ModuleOne } from 'path/to/module/one';
export { default as ModuleTwo } from 'path/to/module/two';
export { SomeNamedModule } from 'path/to/named/module';
// host.js
import * as indexer from 'index';
const moduleName = 'ModuleOne';
const Module = require(indexer[moduleName]);
obscuring it in an eval worked for me, hiding it from the static analyzer ...
if (typeof __CLI__ !== 'undefined') {
eval("require('fs');")
}
Conditional imports could also be achieved with a ternary and require()s:
const logger = DEBUG ? require('dev-logger') : require('logger');
This example was taken from the ES Lint global-require docs: https://eslint.org/docs/rules/global-require
I was able to achieve this using an immediately-invoked function and require statement.
const something = (() => (
condition ? require('something') : null
))();
if(something) {
something.doStuff();
}
Look at this example for clear understanding of how dynamic import works.
Dynamic Module Imports Example
To have Basic Understanding of importing and exporting Modules.
JavaScript modules Github
Javascript Modules MDN
No, you can't!
However, having bumped into that issue should make you rethink on how you organize your code.
Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/
I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.
One can go through the below link to learn more about dynamic imports
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
I know this is not what the question is asking for, but here is my approach to use mocks when using vite. I'm sure we can do the same with webpack and others.
Suppose we have two libraries with same interface: link.js and link-mock.js, then:
In my vite.config.js
export default defineConfig(({ command, mode }) => {
const cfg = {/* ... */}
if (process.env.VITE_MOCK == 1) {
cfg.resolve.alias["./link"] = "./link-mock"; // magic is here!
}
return cfg;
}
code:
import { link } from "./link";
in console we call:
# to use the real link.js
npm run vite
# to use the mock link-mock.js
VITE_MOCK=1 npm run vite
or
package.json script
{
....
"scripts": {
"dev": "vite",
"dev-mock": "VITE_MOCK=1 vite"
}
}

Why does require not behave the same as import when same structure is given

It seems I have a fundamental lack of understanding when it comes to import vs require. From what I've read I know the difference is that require is based on a module loaders like CommonJS while import is actually an ES6 feature.
Assuming the following:
import ExamplePost from 'example-post.md'
This is an example import with MDX JS as appropriate loader and I
set this in my React render function like:
render () {
return <ExamplePost />
}
The above works perfectly fine, but
as I want to dynamically load different Markdown files and I have read that ES6 import are static I intended to go like:
let postName = 'example-post'
const ExamplePost = require(`${postName}.md`)
Unfortunately it doesn't work, I am getting: ExamplePost is not defined
I'm setting both examples at the top of the document. I also inspected both versions and I can see a difference in the outcome:
ES6 import returns: [Function]
Require returns: Object [Module] { default: [Function] }
Help to get me on the right track on why the require above does not work the same?
You import the default export of module and require the module itself.
const ExamplePost = require(`${postName}.md`).default
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Also check Can't require() default export value in Babel 6.x

How can I conditionally import an ES6 module?

I need to do something like:
if (condition) {
import something from 'something';
}
// ...
if (something) {
something.doStuff();
}
The above code does not compile; it throws SyntaxError: ... 'import' and 'export' may only appear at the top level.
I tried using System.import as shown here, but I don't know where System comes from. Is it an ES6 proposal that didn't end up being accepted? The link to "programmatic API" from that article dumps me to a deprecated docs page.
We do have dynamic imports proposal now with ECMA. This is in stage 3. This is also available as babel-preset.
Following is way to do conditional rendering as per your case.
if (condition) {
import('something')
.then((something) => {
console.log(something.something);
});
}
This basically returns a promise. Resolution of promise is expected to have the module. The proposal also have other features like multiple dynamic imports, default imports, js file import etc. You can find more information about dynamic imports here.
If you'd like, you could use require. This is a way to have a conditional require statement.
let something = null;
let other = null;
if (condition) {
something = require('something');
other = require('something').other;
}
if (something && other) {
something.doStuff();
other.doOtherStuff();
}
You can't import conditionally, but you can do the opposite: export something conditionally. It depends on your use case, so this work around might not be for you.
You can do:
api.js
import mockAPI from './mockAPI'
import realAPI from './realAPI'
const exportedAPI = shouldUseMock ? mockAPI : realAPI
export default exportedAPI
apiConsumer.js
import API from './api'
...
I use that to mock analytics libs like mixpanel, etc... because I can't have multiple builds or our frontend currently. Not the most elegant, but works. I just have a few 'if' here and there depending on the environment because in the case of mixpanel, it needs initialization.
2020 Update
You can now call the import keyword as a function (i.e. import()) to load a module at runtime. It returns a Promise that resolves to an object with the module exports.
Example:
const mymodule = await import('modulename');
const foo = mymodule.default; // Default export
const bar = mymodule.bar; // Named export
or:
import('modulename')
.then(mymodule => {
const foo = mymodule.default; // Default export
const bar = mymodule.bar; // Named export
});
See Dynamic Imports on MDN
Looks like the answer is that, as of now, you can't.
http://exploringjs.com/es6/ch_modules.html#sec_module-loader-api
I think the intent is to enable static analysis as much as possible, and conditionally imported modules break that. Also worth mentioning -- I'm using Babel, and I'm guessing that System is not supported by Babel because the module loader API didn't become an ES6 standard.
Import and Export Conditionally in JS
const value = (
await import(`${condtion ? `./file1.js` : `./file2.js`}`)
).default
export default value
Important difference if you use dynamic import Webpack mode eager:
if (normalCondition) {
// this will be included to bundle, whether you use it or not
import(...);
}
if (process.env.SOMETHING === 'true') {
// this will not be included to bundle, if SOMETHING is not 'true'
import(...);
}
require() is a way to import some module on the run time and it equally qualifies for static analysis like import if used with string literal paths. This is required by bundler to pick dependencies for the bundle.
const defaultOne = require('path/to/component').default;
const NamedOne = require('path/to/component').theName;
For dynamic module resolution with complete static analysis support, first index modules in an indexer(index.js) and import indexer in host module.
// index.js
export { default as ModuleOne } from 'path/to/module/one';
export { default as ModuleTwo } from 'path/to/module/two';
export { SomeNamedModule } from 'path/to/named/module';
// host.js
import * as indexer from 'index';
const moduleName = 'ModuleOne';
const Module = require(indexer[moduleName]);
obscuring it in an eval worked for me, hiding it from the static analyzer ...
if (typeof __CLI__ !== 'undefined') {
eval("require('fs');")
}
Conditional imports could also be achieved with a ternary and require()s:
const logger = DEBUG ? require('dev-logger') : require('logger');
This example was taken from the ES Lint global-require docs: https://eslint.org/docs/rules/global-require
I was able to achieve this using an immediately-invoked function and require statement.
const something = (() => (
condition ? require('something') : null
))();
if(something) {
something.doStuff();
}
Look at this example for clear understanding of how dynamic import works.
Dynamic Module Imports Example
To have Basic Understanding of importing and exporting Modules.
JavaScript modules Github
Javascript Modules MDN
No, you can't!
However, having bumped into that issue should make you rethink on how you organize your code.
Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/
I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.
One can go through the below link to learn more about dynamic imports
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports
I know this is not what the question is asking for, but here is my approach to use mocks when using vite. I'm sure we can do the same with webpack and others.
Suppose we have two libraries with same interface: link.js and link-mock.js, then:
In my vite.config.js
export default defineConfig(({ command, mode }) => {
const cfg = {/* ... */}
if (process.env.VITE_MOCK == 1) {
cfg.resolve.alias["./link"] = "./link-mock"; // magic is here!
}
return cfg;
}
code:
import { link } from "./link";
in console we call:
# to use the real link.js
npm run vite
# to use the mock link-mock.js
VITE_MOCK=1 npm run vite
or
package.json script
{
....
"scripts": {
"dev": "vite",
"dev-mock": "VITE_MOCK=1 vite"
}
}

TypeScript ES6 import module "File is not a module error"

I am using TypeScript 1.6 with ES6 modules syntax.
My files are:
test.ts:
module App {
export class SomeClass {
getName(): string {
return 'name';
}
}
}
main.ts:
import App from './test';
var a = new App.SomeClass();
When I am trying to compile the main.ts file I get this error:
Error TS2306: File 'test.ts' is not a module.
How can I accomplish that?
Extended - to provide more details based on some comments
The error
Error TS2306: File 'test.ts' is not a module.
Comes from the fact described here http://exploringjs.com/es6/ch_modules.html
17. Modules
This chapter explains how the built-in modules work in ECMAScript 6.
17.1 Overview
In ECMAScript 6, modules are stored in files. There is exactly one
module per file and one file per module. You have two ways of
exporting things from a module. These two ways can be mixed, but it is
usually better to use them separately.
17.1.1 Multiple named exports
There can be multiple named exports:
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
...
17.1.2 Single default export
There can be a single default export. For example, a function:
//------ myFunc.js ------
export default function () { ··· } // no semicolon!
Based on the above we need the export, as a part of the test.js file. Let's adjust the content of it like this:
// test.js - exporting es6
export module App {
export class SomeClass {
getName(): string {
return 'name';
}
}
export class OtherClass {
getName(): string {
return 'name';
}
}
}
And now we can import it in these three ways:
import * as app1 from "./test";
import app2 = require("./test");
import {App} from "./test";
And we can consume imported stuff like this:
var a1: app1.App.SomeClass = new app1.App.SomeClass();
var a2: app1.App.OtherClass = new app1.App.OtherClass();
var b1: app2.App.SomeClass = new app2.App.SomeClass();
var b2: app2.App.OtherClass = new app2.App.OtherClass();
var c1: App.SomeClass = new App.SomeClass();
var c2: App.OtherClass = new App.OtherClass();
and call the method to see it in action:
console.log(a1.getName())
console.log(a2.getName())
console.log(b1.getName())
console.log(b2.getName())
console.log(c1.getName())
console.log(c2.getName())
Original part is trying to help to reduce the amount of complexity in usage of the namespace
Original part:
I would really strongly suggest to check this Q & A:
How do I use namespaces with TypeScript external modules?
Let me cite the first sentence:
Do not use "namespaces" in external modules.
Don't do this.
Seriously. Stop.
...
In this case, we just do not need module inside of test.ts. This could be the content of it adjusted test.ts:
export class SomeClass
{
getName(): string
{
return 'name';
}
}
Read more here
Export =
In the previous example, when we consumed each validator, each module only exported one value. In cases like this, it's cumbersome to work with these symbols through their qualified name when a single identifier would do just as well.
The export = syntax specifies a single object that is exported from the module. This can be a class, interface, module, function, or enum. When imported, the exported symbol is consumed directly and is not qualified by any name.
we can later consume it like this:
import App = require('./test');
var sc: App.SomeClass = new App.SomeClass();
sc.getName();
Read more here:
Optional Module Loading and Other Advanced Loading Scenarios
In some cases, you may want to only load a module under some conditions. In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.
The compiler detects whether each module is used in the emitted JavaScript. For modules that are only used as part of the type system, no require calls are emitted. This culling of unused references is a good performance optimization, and also allows for optional loading of those modules.
The core idea of the pattern is that the import id = require('...') statement gives us access to the types exposed by the external module. The module loader is invoked (through require) dynamically, as shown in the if blocks below. This leverages the reference-culling optimization so that the module is only loaded when needed. For this pattern to work, it's important that the symbol defined via import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).
Above answers are correct. But just in case...
Got same error in VS Code. Had to re-save/recompile file that was throwing error.
How can I accomplish that?
Your example declares a TypeScript < 1.5 internal module, which is now called a namespace. The old module App {} syntax is now equivalent to namespace App {}. As a result, the following works:
// test.ts
export namespace App {
export class SomeClass {
getName(): string {
return 'name';
}
}
}
// main.ts
import { App } from './test';
var a = new App.SomeClass();
That being said...
Try to avoid exporting namespaces and instead export modules (which were previously called external modules). If needs be you can use a namespace on import with the namespace import pattern like this:
// test.ts
export class SomeClass {
getName(): string {
return 'name';
}
}
// main.ts
import * as App from './test'; // namespace import pattern
var a = new App.SomeClass();
In addition to A. Tim's answer there are times when even that doesn't work, so you need to:
Rewrite the import string, using the intellisense. Sometimes this fixes the issue
Restart VS Code
I had this issue and I had forgotten to export the Class.
In addition to Tim's answer, this issue occurred for me when I was splitting up a refactoring a file, splitting it up into their own files.
VSCode, for some reason, indented parts of my [class] code, which caused this issue. This was hard to notice at first, but after I realised the code was indented, I formatted the code and the issue disappeared.
for example, everything after the first line of the Class definition was auto-indented during the paste.
export class MyClass extends Something<string> {
public blah: string = null;
constructor() { ... }
}
Just in case this may works for you as it did form me, i had this files
//server.ts
class Server{
...
}
exports.Server = Server
//app.ts
import {Server} from './server.ts'
And this actually raised an error but i changed server.ts to
//server.ts
export class Server{
...
}
and it worked 😎👌
Note: i am using this config
"target": "esnext",
"module": "commonjs",
I faced the same issue in a module that has no exports. I used it for side-effects only. This is what the TypeScript docs say about importing side-effects modules:
Though not recommended practice, some modules set up some global state that can be used by other modules. These modules may not have any exports, or the consumer is not interested in any of their exports. To import these modules, use:
import "./my-module.js";
In that situation, you can fix the "File is not a module" error by simply exporting an empty object:
// side-effects stuff
export default {};
I faced the same issue ("File is not a module error") for import js in vue component
import handleClientLoad from "../../../public/js/calendar.js"
I do this and solve it
// #ts-ignore
import handleClientLoad from "../../../public/js/calendar.js"
The file needs to add Component from core hence add the following import to the top
import { Component } from '#angular/core';

Categories