I have a Protractor project which contains such a file:
var FriendCard = function (card) { var webElement = card; var menuButton; var serialNumber; this.getAsWebElement = function () { return webElement; }; this.clickMenuButton = function () { menuButton.click(); }; this.setSerialNumber = function (numberOfElements) { serialNumber = numberOfElements + 1; menuButton = element(by.xpath('.//*[@id=\'mCSB_2_container\']/li[' + serialNumber + ']/ng-include/div/div[2]/i')); }; this.deleteFriend = function () { element(by.css('[ng-click="deleteFriend(person);"]')).click(); element(by.css('[ng-click="confirm()"]')).click(); } }; module.exports = FriendCard;
Path to the file is ./pages/FriendCard.js
.
I have no problems with its import to another file using require()
:
var FriendCard = require('./../pages/FriendCard');
So, I've decided to import this file to the TypeScript file just like that:
import {FriendCard} from './../pages/FriendCard'
I'm using WebStorm. It tells me that (TS2305) it has no exported member 'FriendCard'.
Maybe I have to configure tsconfig.json file somehow, but I still don't know how it works. Could you help me?
The short answer is definitely YES ! but you need some intermediate steps! Please note that you can write plain old JavaScript in a TypeScript project without any problems since JavaScript is a subset of TypeScript, you only need these steps if you are planning to use an external JavaScript library with TypeScript.
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.
You can import the whole module as follows:
import * as FriendCard from './../pages/FriendCard';
For more details please refer the modules section of Typescript official docs.
Recent Updated Solution : We need to tweak the tsconfig.json to allow JS modules import. credits to @paulmest, @ben-winding @crispen-gari solutions below.
{ "compilerOptions": { "allowJs": true } }
I'm currently taking some legacy codebases and introducing minimal TypeScript changes to see if it helps our team. Depending on how strict you want to be with TypeScript, this may or may not be an option for you.
The most helpful way for us to get started was to extend our tsconfig.json
file with this property:
// tsconfig.json excerpt: { ... "compilerOptions": { ... "allowJs": true, ... } ... }
This change lets our JS files that have JSDoc type hints get compiled. Also our IDEs (JetBrains IDEs and VS Code) can provide code-completion and Intellisense.
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With