Webpack 无法识别 Node 的进程模块 [英] Webpack not recognizing Node's process module

查看:85
本文介绍了Webpack 无法识别 Node 的进程模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在十多年没有接触 Javascript 之后,我想到了一个在作为 NodeJS 应用程序实现时效果最好的应用程序.我阅读了现代 JS 生态系统,但和大多数人一样,我很困惑,哈哈.

NodeJS、TypeScript 和 Webpack 的组合似乎是一个不错的选择,但我什至无法让简单的 Hello World 工作.

我写的一个 TypeScript 文件,./src/run_task.ts:

//#!/usr/bin/env 节点/*** @file 主应用程序文件.用户通过运行 `node dist/run_task.js` 来启动应用程序* @作者 Gerard Leenhouts*/从进程"导入 * 作为进程;函数主():数字{控制台日志(进程);console.log(`有 ${process.argv.length} 个参数.`);返回 42;}主要的();

当我手动执行 tsc (tsc -p server.tsconfig.json) 时它工作正常,但是当我执行 webpack 时它似乎在生成的 .js 文件中创建它自己的 process 模块定义.这是其中的一部分:

process.nextTick = 函数(有趣){var args = new Array(arguments.length - 1);如果(参数.长度> 1){for (var i = 1; i < arguments.length; i++) {args[i - 1] = 参数[i];}}queue.push(new Item(fun, args));if (queue.length === 1 && !draining) {运行超时(排水队列);}};//v8 喜欢可预测的对象功能项目(乐趣,数组){this.fun = 有趣;this.array = 数组;}Item.prototype.run = 函数 () {this.fun.apply(null, this.array);};process.title = '浏览器';process.browser = true;process.env = {};process.argv = [];process.version = '';//空字符串以避免正则表达式问题process.versions = {};函数 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 = 函数(名称){throw new Error('process.binding is not supported');};process.cwd = function () { return '/' };process.chdir = 函数(目录){throw new Error('process.chdir 不被支持');};process.umask = function() { return 0;};

我的package.json:

<代码>{"name": "起始页","版本": "1.0.0","description": "作为网络浏览器起始页的自托管网络应用程序","main": "run_task.js",脚本":{"build": "webpack","start": "节点 dist/run_task.js","test": "echo \"Error: no test specified\" && exit 1"},"author": "Gerard Leenhouts","license": "ISC",开发依赖":{"@types/node": "^9.4.6","ts-loader": "^3.5.0","打字稿": "^2.7.2","webpack": "^3.11.0"}}

我的webpack.config.js:

const path = require('path');模块.exports = [{//devtool: 'inline-source-map',条目:'./src/run_task.ts',模块: {规则: [{测试:/\.tsx?$/,用: [{loader: 'ts-loader',选项:{ configFile:'server.tsconfig.json'}}],排除:/node_modules/}]},解决: {扩展名:['.ts'、'.tsx'、'.js']},输出: {文件名:'run_task.js',路径:path.resolve(__dirname, 'dist')}}];

我的server.tsconfig.json:

<代码>{编译器选项":{//"sourceMap": true,"outDir": "./dist/",严格":真实,"noImplicitAny": 真,目标":es6","module": "commonjs","moduleResolution": "节点","esModuleInterop": 真,"baseUrl": "./","paths": { "*": ["node_modules/*", "src/types/*"] },"removeComments": 真},包括":[./src/**/*"]}

我已经浏览了 Webpack 和 TypeScript 文档几个小时了,但似乎无法弄清楚.很可能我正在俯瞰一些简单的东西,但我再也看不到树木的森林了.显然它与模块分辨率有关,但据我所知,配置文件中的一切似乎都很好.感谢任何帮助,提前致谢!

解决方案

它似乎在进程模块中创建了它自己的定义生成的 .js 文件

在您的 webpack.config.js 中,您需要将 target 设置为 node.只需在与 output 相同的级别添加 target: 'node' 即可.这将编译为在类似 Node.js 的环境中使用(使用 Node.js require 加载块,而不接触任何内置模块,如进程、fs 等).文档在这里:https://webpack.js.org/concepts/targets/>

After not touching Javascript for over a decade I had an idea for an app that will work best when implemented as a NodeJS app. I read up on the modern JS ecosystem and like most people I'm thoroughly confused, haha.

Seems like the combination of NodeJS, TypeScript and Webpack is a good way to go, but I'm having issues even getting a simple Hello World working.

The one TypeScript file I wrote, ./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();

When I execute tsc manually (tsc -p server.tsconfig.json) it works fine, but when I execute webpack it seems to create it's own definition of the process module in the resulting .js file. Here's a part of it:

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; };

My 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"
  }
}

My 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')
        }
    }
];

My 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/**/*" ]
}

I've been going through the Webpack and TypeScript documentation for hours now, and can't seem to figure it out. It's quite possible I'm overlooking something simple but I can't see the forest for the trees anymore. Obviously it has something to do with module resolution but everything seems fine in the config files, as far as I can tell. Any help is appreciated, thanks in advance!

解决方案

it seems to create it's own definition of the process module in the resulting .js file

In your webpack.config.js you need to set the target to node. Just add target: 'node' at the same level as output. This will compile for usage in a Node.js-like environment (uses Node.js require to load chunks and not touch any built in modules like process, fs, etc). Docs here: https://webpack.js.org/concepts/targets/

这篇关于Webpack 无法识别 Node 的进程模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆