Cannot find module "shelljs" on including the lib in angular 2 typescript
Asked Answered
M

1

1

I want to include shelljs library to angular 2 typescript. I have included the shelljs.d.ts file to my node_modules/shelljs library.

My package.json

"name": "myproj1",
  "description": "myproj1: A project",
  "typings": {
    "shelljs": {
      "definitions": "node_modules/shelljs/shelljs.d.ts",
      "source": "node_modules/shelljs/global.js"
    }
  },

My webpack.config.js

var path = require('path');
module.exports = {
    entry:  './app/web/boot.ts',
    output: {
        path: path.resolve(__dirname, "js"),
        filename: "bundle.js"
    },
    resolve: {
        extensions:['','.js','.ts']
    },
    module:{
        loaders: [{
            test: /\.ts/,
            loaders: ['ts-loader'],
            exclude: /node_modules/
        }]
    },
    target: 'node'
};

My package.json compiler options:

"compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },

My TS file:

import child = require("shelljs");
somefun(){
 child.exec('node --version',(code, stdout, stderr)=>{
            console.log('Exit code:', code);
            console.log('Program output:', stdout);
            console.log('Program stderr:', stderr);
        });
}

I am getting the error as "Cannot find module 'shelljs'". Please help me to include the library in my project.

Monomer answered 28/4, 2016 at 11:45 Comment(1)
no idea how shell.js works but try let shell = require('shelljs/global'); shell.exec(...Stackhouse
H
1

Use tsd to manage all your typings.

From your project directory:

npm install tsd -g
tsd install node --save
tsd install shelljs --save

Then include the reference to shelljs in your foo.ts:

/// <reference path="typings/shelljs/shelljs.d.ts" />
import {exec} from "shelljs";

exec('node --version', code => {
    console.log('Exit code:', code);
});

Based on the comments, here is the summary:

Using shelljs is only possible in NodeJS environment. This can be either raw nodejs instance, or some projects which contain nodejs in self, like Electron.

Also you should pay attention, which Module System you are using. For NodeJS you can use CommonJS without any further bundlers. But if you compile your TypeScripts for the frontend, where NodeJS is not present, then you should also bundle your CommonJS modules with browserify. Or you can use other types of Modules, like amd or SystemJS, and then in typescript compiler options, you set `"module": "system" for instance. See all options here

Hackett answered 29/4, 2016 at 14:59 Comment(11)
tsd has been updated to typings and when i include it, i get error as the module is always looked under "node_modules" folder. So i installed shelljs npm and placed my typings file inside the node_modules/shelljs folder. Still i getting the error as "cannot find module shelljs". Node.d.ts is available under angular2 ts by default.Monomer
You shouldn't place anything inside the node_modules. Install the typings with tsd for shelljs and include proper path in your file with /// <reference path="shelljs/shelljs.d.ts" />. Note that path is relative to your current .ts file.Hackett
Without installing shelljs in node_modules, i am getting error as follows on compiling.c:\Users\user\Desktop\Samples\Angular_Projects\myProject1\myproj1\node_modules\shelljs doesn't exist (module as directory) With shelljs in node_modules installed, i am getting "Uncaught ReferenceError: require is not defined" during run time with blank screen displayed on my appMonomer
Yes, you have to install the npm install shelljs --save, but you shouldn't modify it, as you wrote "placed my typings file inside the node_modules/shelljs folder". The typings are installed separately for this module: tsd install shelljs --save. So then the issue with ReferenceError: actually it means typescript was successfully compiled and it runs, but the webview doesn't recognize the require method. Do you use Electron? As it is then wired, as electron supports nodejs require.Hackett
no. i am not using electron. I guess the problem is due to the use of webpack. But i dont know how to resolve it. From a example, i tried including target: 'node', node: { global: 'window', crypto: 'empty', process: true, module: false, clearImmediate: false, setImmediate: false } in config. Still the problem remains the sameMonomer
Where does you app runs? In browser? Then you can't use shelljs there, as it doesnt allow to run system shell commands.Hackett
What is your scenario? You want some user navigates to your webpage and you want then to execute some shell command on his machine? Then it is not possible at all. Imagine all the security issues people would have). What commands do you want to run? You can use electron for instance. This is a standalone browser with nodejs inside. It behaves like normal system application. People then download your application, install it and run as normal app. So there, beyond browsers render engine, you can use also nodejs things.Hackett
My scenario: when user clicks on a button in browser, i should navigate to my server, where i should execute a shell command to create, build and run the file and then provide the final file back to user for downloading. I tried using node "child_process" but again it comes back to whatever you have explained me before. Any ways to achieve this?Monomer
Yes, you have to provide the API for this using some NodeJS server. This has nothing to do then with angular. The user clicks the button, and you send then an ajax request to that api, and the endpoint makes all the job and sends back the response. So you have to look towards expressjs. So your application will consist of 2 parts - the frontend (angularjs, browser), and the backend - RESTful endpoints with NodeJS.Hackett
Thanks a lot. I will check with expressjs. Thanks again for your valuable timeMonomer
You are welcome, should you have further questions, fill free to create any.Hackett

© 2022 - 2024 — McMap. All rights reserved.