How to import a self-made module in create-react-app? - javascript

I'm using create-react-app in my ReactJS app with TypeScript, and I would like to import a TypeScript/JavaScript module that I created in another project.
The module consists of a file mymodule.js, in which the code looks approximately like this:
var mymodule;
(function (mymodule) {
var MyClass = /** #class */ (function () {
function MyClass() {
}
MyClass.myMethod = function () {
// code
};
return MyClass;
}());
mymodule.MyClass = MyClass;
})(mymodule || (mymodule = {}));
Then there is the type definition file mymodule.d.ts, which looks like this:
declare module mymodule {
class MyClass {
private static myMethod;
}
}
In my create-react-app project, I placed these two files in the folder /src/vendor, and I want to use the module like this:
import { MyClass } from '../vendor/mymodule';
...
However, Visual Studio Code (i.e. the TypeScript compiler) says
File '.../vendor/mymodule.d.ts' is not a module. ts(2306)
When I run the project, the variables from the module (e.g. the class MyClass) are undefined.
This might be the reason for the error: The library is generated using module: "AMD", but create-react-app seems to enforce module: "esnext".
Edit: Here's the tsconfig.json of the create-react-app project:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"jsx": "react",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true
},
"include": [
"src"
]
}

You can't import the file due to the fact that you are not exporting the module. In order for module loading to work, you should have an export at the bottom of your myModule class file.
export {
mymodule
}

Related

unable to make google-play-billing-validator typescript work

I have been switching to typescript recently, before I used js and it worked perfectly.
I have the following lines in my file:
import Verifier from 'google-play-billing-validator';
var options = {
"email": serviceAccountSub["client_email"],
"key": serviceAccountSub["private_key"],
};
const verif = new Verifier(options);
Now the typescript compiler is telling me that "This expression is not constructable", referring to Verifier.
Now inside the google module we have this code:
declare const Verifier: {
new (options: Options): IVerifier;
};
export default Verifier;
I do not understand what is happening, Verifier should be the default export right?
I'm using this typescript config :
{
"compilerOptions": {
"resolveJsonModule": true,
"outDir": "./dist",
"allowJs": true,
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "nodenext",
"esModuleInterop": true,
},
"include": [
"./**/*"
]
}

Include es5 lib into the stencil web component

I have an external library that is written in the old IIFE style. I have a web component which uses this lib inside. This web component was created with stencil.
Now if I use my web component in some project, I have to include component js file and this external library to the index.html via src file. How can I include this library to the component's compiled code? Is it possible without re-writing it to the es6 module?
This is how my code looks now (in the index.html):
<script src="./myMathLib.js"></script>
<script src="./myWebComponent.js"></script>
I want to have it like this:
<script src="./myWebComponent.js"></script>
This is the code of my component:
import {Component, Prop} from '#stencil/core';
declare var myMathLib: any;
#Component({
tag: 'my-component',
shadow: true
})
export class MyComponent {
#Prop() name: string;
#Prop() age: number;
render() {
return <div>
The age of {this.name} is: {myMathLib.calculate(this.age)}
</div>;
}
}
This is my tsconfig.json:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"allowUnreachableCode": false,
"declaration": false,
"experimentalDecorators": true,
"lib": [
"dom",
"es2017"
],
"moduleResolution": "node",
"module": "esnext",
"target": "es2017",
"noUnusedLocals": true,
"noUnusedParameters": true,
"jsx": "react",
"jsxFactory": "h"
},
"include": [
"src",
"types/jsx.d.ts"
],
"exclude": [
"node_modules"
]
}
This is my stencil.config.ts:
import { Config } from '#stencil/core';
export const config: Config = {
namespace: 'mycomponent',
outputTargets:[
{ type: 'dist' },
{ type: 'docs' },
{
type: 'www',
serviceWorker: null // disable service workers
}
]
};
Somewhere in the root of your project, there should be a stencil.config.ts file. In there you can specify copy tasks. You can read here how to do this: https://stenciljs.com/docs/config#copy
After you set that up correctly and your ../assets/ folder is being copied to your build folder.
You need to copy your all the external js file inside assets folder.
In your render method you can directly refer js file from /assets/
After some research, I figured out that the best option is to use globalScript property from stencil.config.
I added my library to the assets folder and then added the following line to my stencil.config.ts file:
globalScript:'src/assets/myMathLib.js'
After it, I was able to use myMathLib.calculate(this.age) in the code of the component.

Typescript shared path, unable to export const

I'm working on a project where the front-end and the back-end reside in the same directory and both use TypeScript.
I am using a shared path to store some interfaces and constants between the two projects.
But, when I try to export a constant from any file in /shared, I get a :
Error: Cannot find module '#shared/test'
server-config.ts:
"compilerOptions": {
"baseUrl": "./src/server/",
"sourceMap": false,
"module": "commonjs",
"moduleResolution": "node",
"target": "ES2017",
"types": ["node"],
"outDir": "./dist/",
"allowJs": true,
"typeRoots": [
"node_modules/#types"
],
"paths": {
"#shared/*": ["../shared/*"]
},
/shared/test.ts:
// If I remove the following line, no compile error, even finds TheTest
export const TEST = 'test';
export class TheTest {
}
import
// << Module not found (only if I import TEST)
import { TEST, TheTest } from '#shared/test';
export function Foo() {
console.log(TEST);
}

how could I define a global module by typescript and not add to compiled file?

If a have a global module in a.ts:
export = class A(){
}
I want to import this module into a lot of .ts file, but when I do this, the module A will be compile to every file that I import module A.
So how can I define a global module, when I import it, this module will not be add to the compiled file.
my tsconfig.json :
{
"compilerOptions": {
"module": "amd",
"target": "es5",
"sourceMap": false,
"outFile": "index.js",
"moduleResolution": "classic",
"baseUrl": "./",
"paths": {
"jQuery": ["types/jquery.d.ts"],
}
},
"exclude": [
"node_modules"
]
}

Consuming default export with Typescript

I would like to use a small javascript library within a typescript project. (For the full example see here).
The javascript library defines the following:
"use strict";
exports.__esModule = true;
exports["default"] = functionOfInterest;
function functionOfInterest(val) { }
module.exports = exports["default"];
This has been typed using a .d.ts file as:
export default function functionOfInterest(val: number): void;
In a typescript file I use:
import functionOfInterest from "the-package";
functionOfInterest(1); // invoke it.
This is compiled to:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var functionOfInterest_1 = require("the-package");
functionOfInterest_1.default.apply(void 0, 1);
This errors with:
TypeError: Cannot read property 'apply' of undefined
My tsconfig.json file is:
{
"compilerOptions": {
"outDir": "js",
"module": "commonjs",
"declaration": true,
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "ts",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true
},
"exclude": [
"node_modules",
"build"
]
}
I'm sure there's just a simple configuration error somewhere but I can't figure it out at the moment.
Typescript 2.2.2
You have to use:
import functionOfInterest = require("the-package");
(functionOfInterest as any)(1);
** Alternatively **
You can change the definition file to:
declare function functionOfInterest(val: number): void;
export = functionOfInterest;
And then consume without the cast to any:
import functionOfInterest = require("the-package");
functionOfInterest(1);
Try this:
import * as _ thePackage from "the-package";
thePackage.functionOfInterest(1);

Categories

Resources