NodeJS Webpack无法识别节点的进程模块

hrysbysz  于 2023-01-30  发布在  Node.js
关注(0)|答案(2)|浏览(149)

在十多年没有接触Javascript之后,我有了一个想法,当作为NodeJS应用程序实现时,我会工作得最好。我读了现代JS生态系统,像大多数人一样,我完全糊涂了,哈哈。
看起来NodeJS、TypeScript和Webpack的组合是一个很好的方法,但是我甚至连一个简单的Hello World都有问题。
我写的一个TypeScript文件,./src/run_task.ts

// #!/usr/bin/env node
/**
 * @file Main application file. Users start the app by running `node dist/run_task.js`
 * @author Gerard Leenhouts
 */

import * as process from "process";

function main(): number {
    console.log(process);
    console.log(`Got ${process.argv.length} arguments.`);
    return 42;
}

main();

当我手动执行tsctsc -p server.tsconfig.json)时,它工作正常,但当我执行webpack时,它似乎在生成的.js文件中创建了自己的process模块定义。

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

我的package.json

{
  "name": "startpage",
  "version": "1.0.0",
  "description": "Self hosted web app to function as a web browser startpage",
  "main": "run_task.js",
  "scripts": {
    "build": "webpack",
    "start": "node dist/run_task.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Gerard Leenhouts",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^9.4.6",
    "ts-loader": "^3.5.0",
    "typescript": "^2.7.2",
    "webpack": "^3.11.0"
  }
}

我的webpack.config.js

const path = require('path');

module.exports = [
    {
        // devtool: 'inline-source-map',
        entry: './src/run_task.ts',
        module: {
            rules: [
                {
                    test: /\.tsx?$/,
                    use: [
                        {
                            loader: 'ts-loader',
                            options: { configFile: 'server.tsconfig.json' }
                        }
                    ],
                    exclude: /node_modules/
                }
            ]
        },
        resolve: {
            extensions: [ '.ts', '.tsx', '.js' ]
        },
        output: {
            filename: 'run_task.js',
            path: path.resolve(__dirname, 'dist')
        }
    }
];

我的server.tsconfig.json

{
    "compilerOptions": {
        // "sourceMap": true,
        "outDir": "./dist/",
        "strict": true,
        "noImplicitAny": true,
        "target": "es6",
        "module": "commonjs",
        "moduleResolution": "node",
        "esModuleInterop": true,
        "baseUrl": "./",
        "paths": { "*": ["node_modules/*", "src/types/*"] },
        "removeComments": true
    },
    "include": [ "./src/**/*" ]
}

我已经看了Webpack和TypeScript文档几个小时了,但似乎还是弄不明白。很可能我忽略了一些简单的东西,但我再也看不到树了。显然这与模块解析有关,但据我所知,配置文件中的一切似乎都很好。任何帮助都很感激,提前感谢!

hl0ma9xz

hl0ma9xz1#

它似乎在生成的.js文件中创建了自己的流程模块定义
在你的webpack.config.js中,你需要把target设置为node。只需要把target: 'node'添加到和output相同的级别。这将编译成在类似于Node.js的环境中使用(使用Node.js需要加载块,并且不接触任何内置模块,如process,fs等)。https://webpack.js.org/concepts/targets/

qoefvg9y

qoefvg9y2#

Webpack的默认编译版本为目标“web”。因此,要解决您的问题,只需使用目标值“node”。
{目标:“节点”}
因为客户端代码也可以包含一些节点js的全局变量,如“process.env”。所以webpack在web目标构建中多边形填充这些变量。
更多更高级的case和控件。“node”属性也可以直接使用。https://v4.webpack.js.org/configuration/node/

相关问题