简体   繁体   English

使用 webpack 在浏览器中使用 require 模块

[英]Using webpack to use require modules in browser

Tried for the past 2 days to use require('modules') in the browser with webpack, when I could do the same thing in browserify in 5 minutes...过去 2 天尝试在带有 webpack 的浏览器中使用 require('modules') ,当时我可以在 5 分钟内在 browserify 中做同样的事情......

Here's my webpack.config.js这是我的webpack.config.js

var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var nodeModules = {};
fs.readdirSync('node_modules')
  .filter(function(x) {
    return ['.bin'].indexOf(x) === -1;
  })
  .forEach(function(mod) {
    nodeModules[mod] = 'commonjs ' + mod;
  });

module.exports = {
    entry: "./main.js",
    output: {
        filename: "bundle.js"
    }
}

However, no matter what I do I get some sort of error.但是,无论我做什么,我都会遇到某种错误。 Currently I am getting:目前我得到:

bundle.js:390 Uncaught Error: Cannot find module "net"

and when I run webpack it throws these errors: http://pastebin.com/RgFN3uYm当我运行 webpack 时,它会抛出这些错误: http ://pastebin.com/RgFN3uYm

I followed https://webpack.github.io/docs/tutorials/getting-started/ and http://www.pauleveritt.org/articles/pylyglot/webpack/ yet I still get these errors.我遵循了https://webpack.github.io/docs/tutorials/getting-started/http://www.pauleveritt.org/articles/pylyglot/webpack/但我仍然遇到这些错误。

I've tried to run it with this: webpack ./main.js -o bundle.js Yet it still doesn't work.我试图用这个来运行它: webpack ./main.js -o bundle.js但它仍然不起作用。

How can this be resolved?如何解决这个问题?

You should add directories to resolve eg您应该添加目录来解决例如

 resolve: {
        modulesDirectories: ['./app/', './node_modules']
 }

Update: Add json loader更新:添加 json 加载器

npm install --save-dev json-loader

module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' }
    ]
  }

also fs, net, tls are libraries for node.js not for in-browser usage. fs、net、tls 也是 node.js 的库,不用于浏览器内使用。 You should add:你应该添加:

node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }

What is your folder structure?你的文件夹结构是什么?

You should have:你应该有:

packages.json
node_modules/net/
webpack.config.js
src/main.js

Then on main.js add然后在 main.js 添加

var net = require('net');

On webpack.config.js:在 webpack.config.js 上:

const path = require('path');

const PATHS = {
    src: path.join(__dirname, 'src'),
    dist: path.join(__dirname, 'dist')
};

module.exports = {
    entry: path.join(PATHS.src, 'main.js'),
    output: {
        path: PATHS.dist,
        filename: 'bundle.js'
    }
}

Run webpack , and this is important, on the index.html, point to the bundle file, not the main.js!运行webpack ,这很重要,在 index.html 上,指向包文件,而不是 main.js!

Node modules can't be run from the browser.节点模块不能从浏览器运行。

It is, sadly, as simple as that.可悲的是,就是这么简单。 Let's take a step back.让我们退后一步。 From the official website :来自官方网站

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js® 是基于 Chrome 的 V8 JavaScript 引擎构建的 JavaScript 运行时。

It may seem like a detail, but it is not, per se , meant as a JavaScript runtime in a browser.它可能看起来像是一个细节,但它本身并不意味着浏览器中的 JavaScript 运行时。 Being a JavaScript runtime however, it can interpret and run javascript code, with added functionnality distinct from what we can do in a browser, for instance the require() function.然而,作为一个 JavaScript 运行时,它可以解释和运行 javascript 代码,增加了与我们在浏览器中可以做的不同的功能,例如require()函数。 It is built in Node, but not in V8.它是在 Node 中构建的,但不是在 V8 中构建的。

What node also allows, is to write modules.节点还允许编写模块。 You could write a node module in c++, compile it and import it within Node context.您可以用 C++ 编写一个节点模块,编译它并在 Node 上下文中导入它。 This is an incredible strength, because it allows javascript to have access to lower level functionnality, which in turn allowed servers to be written in javascript.这是一个令人难以置信的优势,因为它允许 javascript 访问较低级别的功能,这反过来又允许使用 javascript 编写服务器。

Low level functionalities are not available in the browser.低级功能在浏览器中不可用。

Let's consider this:让我们考虑一下:

const fs = require('fs');

What is it even supposed to mean, if run in a browser?如果在浏览器中运行,它甚至应该是什么意思? What filesystem?什么文件系统? I daresay that in no event, ever, should I want any random website I consult to gain access to the filesystem of the machine it runs on.我敢说,在任何情况下,我都不应该想要我咨询的任何随机网站来访问它运行的机器的文件系统。 In the case of a server, in a Node environment, accessing the filesystem is a necessity.在服务器的情况下,在 Node 环境中,访问文件系统是必要的。

Node modules, such as fs, tls, or net, use low level functionality that have no equivalent in a browser, be it for logical ("what filesystem?") or security ("no, your javascript code should not be able to create raw tcp connections") reasons.节点模块,例如 fs、tls 或 net,使用在浏览器中没有等效项的低级功能,无论是逻辑(“什么文件系统?”)还是安全性(“不,您的 javascript 代码不应该能够创建原始 tcp 连接”)原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM