3

I've found this answer, but it didn't solve my problem.

I'm just learning TypeScript.

What I'm doing is as simple as this:

import * as child from 'child_process';

Which triggers this error:

TSError: ⨯ Unable to compile TypeScript
db\installDB.ts (1,24): Cannot find module 'child_process'. (2307)

What I thought is: It's not finding 'child_process' because I have no typings for it, so I added @types/node on the hope it would now find it. It didn't.

What is the problem?

This is my tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "allowJs": true
    },
    "include": [
        "./db/**/*",
        "./src/**/*"
    ]
}
Community
  • 1
  • 1
Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • What type of module is `child_process`? The simplest way to import an ambient module is to use the shorthand described in https://www.typescriptlang.org/docs/handbook/modules.html#working-with-other-javascript-libraries – shusson Feb 16 '17 at 00:37

2 Answers2

0

Try this syntax:

import child = require('child_process');

This is a commonjs style import, used for nodejs modules, instead of the current ES6-style import you have currently.

Laurence Dougal Myers
  • 1,004
  • 1
  • 8
  • 17
0

If you have webpack.config.js

Add following array to devConfig and prodConfig in your webpack.config.json

 externals: [
(function () {
    var IGNORES = ["fs","child_process","electron","path","assert","cluster","crypto","dns","domain","events","http","https","net","os","process","punycode","querystring","readline","repl","stream","string_decoder","tls","tty","dgram","url","util","v8","vm","zlib"];
    return function (context, request, callback) {
        if (IGNORES.indexOf(request) >= 0) {
            return callback(null, "require('" + request + "')");
        }
        return callback();
    };
})()
],

This will ignore modules listed in IGNORES array.

Then, in your 'Typescript' file.

declare var require:any;
...
...
var exec = require('child_process');

If you don't have webpack.config and your project is working on webpack. You can find it in "node_modules/app_scripts/config". Copy webpack.config from that path and save it in config folder at the root of your project and paste the following code to your package.json

"config": {
   "ionic_bundler": "webpack",
   "ionic_webpack": "./config/webpack.config.js"
 },

If you have SystemJS

Add following code to system.config.js

 System.config({
  map: {
    'child_process': '@node/child_process'
  }
});
Shreenil Patel
  • 1,054
  • 1
  • 9
  • 20