Harish Vangavolu
Harish Vangavolu

Reputation: 1025

Reading NodeJS process.argv in webpack compiled JavaScript

I'm trying to compile a simple TS file with webpack (via 'awesome-typescript-loader') that should read command line arguments.

However, I believe the compiled JS is redefining the Node 'process' variable with a closure - making process.argv 'undefined'.

TL;DR: How do I read command line arguments with webpack-compiled JS?

a.ts

console.log(process.argv[2]);

webpack.config.js

const path = require('path');

module.exports = {
    resolve:{
      extensions: ['.ts']
    },
    module: {
      rules: [{
          test: /\.ts$/,
          loaders: ['awesome-typescript-loader'],
          include: [
              path.resolve(__dirname, "src")
          ]
      }]
    },
    entry: {
        a: "./src/a.ts"
    },
    output: {
        path: path.resolve(__dirname, 'output'),
        filename: '[name].js'
    }
};

package.json

{
  "name": "my-proj",
  "version": "1.0.0",
  "description": "some purpose",
  "scripts": {
    "start:a": "rimraf output/a.js & webpack --watch && node output/a.js myarg",
    "lint": "tslint \"src/*.ts\"",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "javascript",
    "node"
  ],
  "author": "some guy",
  "license": "ISC",
  "dependencies": {
    "@types/lodash": "^4.14.56",
    "core-js": "^2.4.1",
    "lodash": "^4.17.4",
    "mathjs": "^3.10.0",
    "path": "^0.12.7",
    "rxjs": "^5.2.0",
    "ts-loader": "^2.0.2",
    "typings": "^2.1.0",
    "yargs": "^7.0.2"
  },
  "devDependencies": {
    "@types/node": "^7.0.8",
    "awesome-typescript-loader": "^3.1.2",
    "compression-webpack-plugin": "^0.3.2",
    "concurrently": "^3.4.0",
    "copy-webpack-plugin": "^4.0.1",
    "cross-env": "^3.2.4",
    "external-loader": "^0.1.1",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.10.1",
    "nodemon": "^1.11.0",
    "null-loader": "^0.1.1",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.6.1",
    "tslint": "^4.5.1",
    "typescript": "^2.2.1",
    "webpack": "^2.2.1",
    "webpack-merge": "^4.1.0"
  }
}

For building without script simply run: "webpack", go to output folder, and run "node a.js myarg"

Upvotes: 2

Views: 2383

Answers (1)

Michael Jungo
Michael Jungo

Reputation: 32992

By default webpack creates a bundle that is meant to be run in the browser. Browsers don't have process, so you can't access command line arguments. But as you try to read command line arguments, you probably want to build an app that is meant to be run in Node.js, not in the browser. You can do this by setting the target option to node.

Add this to your webpack config:

target: 'node'

Upvotes: 4

Related Questions