require('child_process')函数中的错误未定义 - TypeScript

时间:2016-08-05 12:27:30

标签: node.js typescript gulp

获取错误:

zone.js:260 Uncaught EXCEPTION: Error in ./AppComponent class AppComponent - inline template:8:48
ORIGINAL EXCEPTION: ReferenceError: require is not defined
ORIGINAL STACKTRACE:
ReferenceError: require is not defined
    at AppComponent.performCmdOperation (http://localhost:8000/app/app.component.js:43:67)

app.component.ts

export class AppComponent{

SelectType = EnumSelectType;
selectedSection: SelectType = EnumSelectType[EnumSelectType.Home];
selectPage(selectType:EnumSelectType) {
    console.log('Global : ' + EnumSelectType[selectType]);
    this.selectedSection = EnumSelectType[selectType];
    console.log(this.selectedSection + ' selected');
}

performCmdOperation(){
    console.log('in perform action');
    const exec = require('sdk/system/child_process').exec; //this is the point where I'm getting error.
    exec('ipconfig', (error, stdout, stderr) => {
        if (error) {
            console.error(`exec error: ${error}`);
            return;
        }
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
    });
}

请帮我找到问题。使用'child_process'是否需要import missing or any dependency

我当前的依赖是

"bootstrap": "^3.3.6",

"@angular/common": "2.0.0-rc.4",
"@angular/compiler": "2.0.0-rc.4",
"@angular/core": "2.0.0-rc.4",
"@angular/http": "2.0.0-rc.4",
"@angular/platform-browser": "2.0.0-rc.4",
"@angular/platform-browser-dynamic": "2.0.0-rc.4",
"@angular/router": "2.0.0-rc.1",
"@angular/router-deprecated": "2.0.0-rc.1",
"@angular/upgrade": "2.0.0-rc.4",

"systemjs": "0.19.27",
"es6-shim": "^0.35.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12"

如果需要修改 gulpfile.ts 。请指示如何在gulpfile中添加'child_process'。

2 个答案:

答案 0 :(得分:2)

请尝试改为child_process,例如:

const exec = require('child_process').exec;

老实说,不确定你想要实现什么,因为它看起来像一个在浏览器中运行的Angular 2项目,但是child_process是一个内置的Node.js组件,在服务器环境中运行。

更新:

在Gulp gulpfile的上下文中,这是一个如何使用child_process来调用外部可执行文件的示例 - 在这种情况下是dotnet CLI。

var ps = require("child_process");
gulp.task("serve:prod", function () {
    const dotnetPs = ps.exec("dotnet run");
    // redirect standard output of the child process to the console.
    dotnetPs.stdout.on("data", function(data) { console.log(data.toString()); });
    dotnetPs.stderr.on("data", function(data) { console.error(data.toString()); });
});

答案 1 :(得分:0)

使用“”双引号。您可能会尝试在CLI中运行,并且很有可能是因为引号。