我正在尝试使用webpack(通过'awesome-typescript-loader')编译一个简单的TS文件,该文件应该读取命令行参数。
但是,我相信已编译的JS正在使用闭包重新定义Node'进程'变量 - 制作process.argv'undefined'。
TL; DR :如何使用webpack编译的JS读取命令行参数?
console.log(process.argv[2]);
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'
}
};
{
"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"
}
}
对于没有脚本的构建,只需运行:“webpack”,转到输出文件夹,然后运行“节点a.js myarg”
答案 0 :(得分:2)
默认情况下,webpack会创建一个要在浏览器中运行的捆绑包。浏览器没有process
,因此您无法访问命令行参数。但是当您尝试读取命令行参数时,您可能希望构建一个应在Node.js中运行的应用程序,而不是在浏览器中运行。您可以将target
选项设置为node
。
将此添加到您的webpack配置:
target: 'node'