Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 295
Rohit Tigga Avatar asked Oct 23 '16 20:10

Rohit Tigga


People also ask

What kind of modules can webpack support?

Webpack supports the following module types natively: ECMAScript modules. CommonJS modules. AMD modules.

Does webpack include node_modules?

Webpack builds a dependency graph used internally Now all modules that are used in your app are included in the dependency graph. Your project have many installed dependencies in the node_modules folder that should not be included in your client-side JavaScript production bundle.

Can I use modules without webpack?

With JavaScript modules fully supported in every major browser, savvy developers can now deliver production-ready apps without Webpack.

Do I need webpack for ES6 modules?

For most browsers, yes, you can accomplish getting all needed code to the browser with just ES6 modules, without Webpack.


3 Answers

You should add directories to resolve e.g.

 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'
  }
like image 98
Piotr Labunski Avatar answered Oct 13 '22 22:10

Piotr Labunski


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!

like image 45
Luan Nico Avatar answered Oct 13 '22 22:10

Luan Nico


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.

like image 20
Félix Adriyel Gagnon-Grenier Avatar answered Oct 13 '22 22:10

Félix Adriyel Gagnon-Grenier