简体   繁体   中英

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...

Here's my 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

I followed https://webpack.github.io/docs/tutorials/getting-started/ and http://www.pauleveritt.org/articles/pylyglot/webpack/ yet I still get these errors.

I've tried to run it with this: webpack ./main.js -o bundle.js Yet it still doesn't work.

How can this be resolved?

You should add directories to resolve eg

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

Update: Add json loader

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. 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

var net = require('net');

On 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!

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.

It may seem like a detail, but it is not, per se , meant as a JavaScript runtime in a browser. 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. It is built in Node, but not in 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. 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.

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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