I was wondering if it's possible to use the content of a ts variable and use it in js file ?
I'm feeling trapped now I realize that I don't know how can I achieve it.
Please send me any suggestion easy to implement if possible.
My ts file with the printedOption that I want to use in my js file.
The content of this variable is the value of my select input.
validateLuggages() {
this.printedOption = this.selectedOption;
this.http.get(`/routes/luggages`)
.subscribe((data) => {
this.parsedForLuggages = data;
})
return this.printedOption;
}
Now, How can I create the instance and use this variable in my JS file ?
To use any typescript variable inside javascript code you may firstly export the variable in typescript file which you want to use in the js file.
Then, you can simply use the import statement and import the variable from the correct path.
You can check the example below and refer the link for better clarity. LINK
// Add to tsconfig.json:
{
"compilerOptions": {
...
"allowJs": true
...
}
}
import MyModule from './../pages/MyModule';
Related
I have a typescript file in which there are some functions for validating objects of different classes. So, I have to import those classes into the ts file. For instance,
import { UserDetail } from "../../entity/user/userDetail";
The following block of code depicts a function which is used for validating the objects of the mentioned class.
export function validateSignUpData(userDetail:UserDetail):Array<String>{
let errorMessages = new Array<String>();
/* Some Code */
As you can see the imported class has been used as the function's input type. Now the problem is that it seems we are not allowed to use both import and module.exports simultaneously! Therefore, I am not able to use require in order to get the mentioned function in the Node server file.
When I add the following block of code to my ts file, the following exception is thrown!
module.exports = validateSignUpData;
TypeError: Cannot assign to read only property 'exports' of object '# object'
Question: How can I use all import, modules.export, and export in the same ts file?
I will be glad if someone can help me with the situation.
Thank You
Of course you're able to import that function with require. Just do it like this:
const {validateSignUpData} = require('./my-module.js')
And pay attention to require the compiled javascript file, not the typescript file. They may be in different folders, depending on your build setup.
Is it possible to import named exports dynamically?
I have a file, banana.js with hundreds of named exports. Id like to import them on demand. Is this possible? And if it is, will it only load that export and not all?
I know its possible to import them dynamically from individual files but I want them in the same file.
Example below..
// banana.js
export const banana_1 = {
..
}
export const banana_2 = {
..
}
// main.js
const currentPage = 1
async getSomething(){
let { `banana_${currentPage}` } = await import('./banana.js');
const foo = `banana_${currentPage}`
}
Fyi im using Vue.js
From what I know, you might have to use require('./banana.js') here. Please note that require is synchronous, so need for await. If you use eslint and it forbids usage of require, just add // eslint-disable-line to the end of that line. BTW, I don't know Vue at all.
About the object you import, you should probably make an array instead of suffixing each export with a number.
Edit: I just realized that dynamic imports are a thing not only possible with require, so ignore the first paragraph.
Based on your response to my question I offer the following solution. I understand not wanting to deploy and use a full database solution for the sake of hot loading some JSON objects. I'm unsure of your use case and other details related to your project.
You can use a self contained database like SQLite. Instead of setting up a NoSQL or SQL server. You can instead just store what you need to the SQLite file. Since Vue requires Node.js you can use the Node.js SQLite3 library https://www.npmjs.com/package/sqlite3.
I hope this helps.
I have an angular 8 library I'm creating and it's going to utilize the insane.js npm package. Because insane is JavaScript, I need to make it so that my typescript service recognizes the insane function. I used dts-gen to create an insane.d.ts file as there is no #types/insane package. However, I can't use the import in my service unless I place the insane.d.ts file within the /node_modules/insane/ folder. That said, I'm at a loss on how to put this file in with my code and recognize the insane function. Every time I move the file out of that directory, I receive an error on my import line saying:
Could not find a declaration file for module 'insane'. 'c:/TFS/repo/amrock-simple-mde/projects/simple-mde/node_modules/insane/insane.js' implicitly has an 'any' type.
I've provided a stackblitz link here to help describe what I'm experiencing. I hope it helps. Check out the SanitizerService under the shared folder to get an idea of what I was trying to do. I'm trying to do something to the effect of:
import { Injectable } from '#angular/core';
import * as insane from 'insane'; // line where error is
#Injectable({
providedIn: 'root'
})
export class SanitizerService {
constructor() { }
sanitize(content: string): string {
return insane(content, {
allowedAttributes: {
a: ['name', 'target']
}
});
}
}
I'd expect the import to recognize the insane.d.ts, but it doesn't. Can anyone help me figure out what I'm missing?
You'll want to use a declare module statement for this:
declare module 'insane' {
// ...
}
Essentially wrap your whole .d.ts file in the declare module block and remove all existing declare keywords since those are not valid inside a declare module block.
Secondly, make sure that the .d.ts file is included by TypeScript. Usually the easiest way to do this is to specify it in the include option of your tsconfig.json.
Updated Stackblitz
I want to share a complex typescript exported function to a simple HTML - javascript website
I tried to use npm tsc to transform the file into javascript, but generated files have "exports" functions that creates errors in the browser console.
myFunction.ts
export const getTest = (test: any) => {
// Change test object
return test;
};
generated myFunction.js
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTest = function (test) {
// Change test object
return test;
};
Browser console actually warning me "Uncaught ReferenceError: exports is not defined" when I try to include the file with a script tag in HTML file.
What am I doing wrong?
In order to use the original myFunction.ts file all you need to do is this:
Remove the typing and change the extension to .js:
export const getTest = (test) => {
// Change test object
return test;
};
And then, in your HTML file's <script> tag for that JavaScript file, make sure you set the type attibute to module like so:
<script type="module" src="myFunction.js"></script>
Finally, you'll need to import that functionality where you intend to use it.
That should do it as long as you consider browser compatibility:
ES6 Modules
To make this ultimately clear, here is a Plunkr to demonstrate what I mean.
The export keyword creates a module, which can only be used with a module system (such as webpack).
Either use a module system or drop export to create a normal file that creates global names.
I have a jsx file using React components with Reflux. There is only one tiny action:
var ClickedAction = Reflux.createActions([
'clicked'
]);
How can I move this action to another file? According to the JSX documentation, it should be easy to include other files:
// import all classes that do not start with "_" from "a.jsx"
import "a.jsx";
I tried to move it in actions/clickedAction.jsx (or .js) and import it using import "actions/clickedActions.jsx" but I keep getting Illegal import declaration. How can I achieve this?
I am not using RequireJS and would like to avoid it if possible. One alternative solution I have found is to include this in the HTML file,
<script type='text/javascript' src='xxxxx/actions/clickedAction.js")'></script>
, but this is not ideal and would like to find another way. Thanks for your attention and help.
If you use Babel:
export default ClickedAction; // in action file
Otherwise, use old modules:
module.exports = ClickedAction; // in action file
require('actions/clickedActions.jsx'); // in another file