Reputation: 1055
Ive just started experimenting with TypeScript and I have a following project structure:
-src
| index.ts
| MyClass.ts
-node_modules
-npm_js_module
| index.js
| utils.js
- src
| someModuleFile.js
| someModuleFile2.js
I need to use functions from npm_js_module/index.js (and from pm_js_module/src but these are required by index.js) in MyClass.ts. This module is untyped and has no typing available online by someone else. Is it even possible to use untyped JavaScript NPM module in typescript project?
When I am trying to compile this project I am getting this error:
error TS6059: File '/node_modules/npm_js_module/index.js' is not under 'rootDir' '/src'. 'rootDir' is expected to contain all source files.
error TS6059: File '/node_modules/npm_js_module/utils.js'' is not under 'rootDir' '/src'. 'rootDir' is expected to contain all source files.
My tsconfig.json looks like this:
{
"compilerOptions": {
"moduleResolution": "node",
"module": "commonjs",
"target": "es2017",
"outDir": "./bin",
"rootDir": "./src",
"sourceMap": true,
"allowJs" : true,
"baseUrl" : "./",
"paths": {
"*" : ["./node_modules/@types/*", "*"]
}
},
"files": [
"./node_modules/@types/node/index.d.ts",
"./node_modules/npm_js_module/index.js"
],
"include": [
"src/**/*.ts",
"./node_modules/npm_js_module/*"
],
"exclude": [
"./node_modules"
]
}
and package.json like this:
{
"name": "myproject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^8.0.30"
},
"dependencies": {
"npm_js_module": "^1.2.3"
}
}
I am using this way to import that module: import * as mymodule from 'npm_js_module';
where VScode shows this error in a code: Property 'login' does not exist on type '(loginData: any, options: any, callback: any) => void'.
and when I try to compile this there are errors like I wrote above.
Upvotes: 4
Views: 4204
Reputation: 2395
Well there are 3 possible solutions for your problem.
import jsModule = require('npm_js_module');
The first solution should work for you, just require it as a normal node.js module. (If you are using the latest version of node 8.5 you will be able to use ES6 import style by activating the special flag node --experimental-modules main.mjs
) but I dont recommend it since it's not finallized..
Upvotes: 1
Reputation: 3241
It's not crystal clear but it is buried in the documentation:
If you scroll down, you'll see a section labeled: export = and import = require()
When importing a module using export =, TypeScript-specific import module = require("module") must be used to import the module.
And that shows an example:
import zip = require("./ZipCodeValidator");
Hope this helps.
Upvotes: 2