Running gunjs with Reactjs and webpack throws Reference Error in console

匿名 (未验证) 提交于 2019-12-03 00:57:01

问题:

I am trying to install gun.js and run it inside a Reactjs webpack bundled app

var path = require('path'),     webpack = require('webpack');  module.exports = {     devtool: 'source-map',     target: 'node',     node: {         fs: 'empty'     },     entry: {         workboard: './src/workboard/main.js'     },     output: {         path: __dirname, filename: '/public/[name]/js/bundle.js'     },     module: {         loaders: [             {                 test: /.js?$/,                 loader: 'babel-loader',                 exclude: /node_modules/,                 query: {                     presets: ['es2015', 'react', 'stage-2', 'stage-1']                 }             }         ],         noParse: [/aws-sdk/]     },     plugins: [         new webpack.DefinePlugin({ "global.GENTLY": false })     ] }; 

package.json looks like this

{   "name": "workbench",   "version": "1.0.0",   "description": "My local workbench",   "main": "index.js",   "scripts": {     "test": "echo \"Error: no test specified\" && exit 1",     "start": "cd public && serve"   },   "author": "kn@unisport.dk",   "license": "ISC",   "dependencies": {     "babel-core": "^6.7.7",     "babel-preset-stage-1": "^6.5.0",     "babel-preset-stage-2": "^6.5.0",     "fetch": "^1.0.1",     "react": "^0.14.8",     "react-dom": "^0.14.8",     "react-router": "^2.3.0"   },   "devDependencies": {     "babel-core": "^6.5.2",     "babel-loader": "^6.2.4",     "babel-preset-es2015": "^6.5.0",     "babel-preset-react": "^6.5.0",     "bufferutil": "^1.2.1",     "gun": "^0.3.992",     "loader-utils": "^0.2.15",     "url": "^0.11.0",     "utf-8-validate": "^1.2.1",     "webpack": "^2.1.0-beta.5"   } } 

js test code in main.js looks like this

/**  * Main.js  */ 'use strict';  /**  * Setup Gun  * TODO: add peers  */ var Gun = require('gun'); var gun = Gun();  var React = require('react'); var ReactDom = require('react-dom');  var App = React.createClass({     render() {         return <div>Hello</div>     } });  var ROOT = document.getElementById('appmount');  ReactDom.render(     <App />,     ROOT ); 

but when I load index.html that includes bundle.js I get this error in the console

Uncaught ReferenceError: require is not defined  module.exports = require("url");   /*****************  ** WEBPACK FOOTER  ** external "url"  ** module id = 21  ** module chunks = 0  **/ 

what is it that I'm missing?

Update Changing node to 'web' as suggested, but this gives me

ERROR in ./~/ws/lib/WebSocketServer.js Module not found: Error: Can't resolve 'tls' in '/Users/kn/Documents/workbench/node_modules/ws/lib'  @ ./~/ws/lib/WebSocketServer.js 15:10-24  ERROR in ./~/diffie-hellman/lib/primes.json Module parse failed: /Users/kn/Documents/workbench/node_modules/diffie-hellman/lib/primes.json Unexpected token (2:11) You may need an appropriate loader to handle this file type. | { |     "modp1": { |         "gen": "02", |         "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"  @ ./~/diffie-hellman/browser.js 2:13-41  ERROR in ./~/elliptic/package.json Module parse failed: /Users/kn/Documents/workbench/node_modules/elliptic/package.json Unexpected token (2:9) You may need an appropriate loader to handle this file type. | { |   "_args": [ |     [ |       {  @ ./~/elliptic/lib/elliptic.js 5:19-45  ERROR in ./~/parse-asn1/aesid.json Module parse failed: /Users/kn/Documents/workbench/node_modules/parse-asn1/aesid.json Unexpected token (1:25) You may need an appropriate loader to handle this file type. | {"2.16.840.1.101.3.4.1.1": "aes-128-ecb", | "2.16.840.1.101.3.4.1.2": "aes-128-cbc", | "2.16.840.1.101.3.4.1.3": "aes-128-ofb",  @ ./~/parse-asn1/index.js 2:12-35 

Installing tls results in this error

    ERROR in ./~/diffie-hellman/lib/primes.json     Module parse failed: /Users/kn/Documents/workbench/node_modules/diffie-hellman/lib/primes.json Unexpected token (2:11)     You may need an appropriate loader to handle this file type.     | {     |     "modp1": {     |         "gen": "02",     |         "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"      @ ./~/diffie-hellman/browser.js 2:13-41      ERROR in ./~/elliptic/package.json     Module parse failed: /Users/kn/Documents/workbench/node_modules/elliptic/package.json Unexpected token (2:9)     You may need an appropriate loader to handle this file type.     | {     |   "_args": [     |     [     |       {      @ ./~/elliptic/lib/elliptic.js 5:19-45      ERROR in ./~/parse-asn1/aesid.json     Module parse failed: /Users/kn/Documents/workbench/node_modules/parse-asn1/aesid.json Unexpected token (1:25)     You may need an appropriate loader to handle this file type.     | {"2.16.840.1.101.3.4.1.1": "aes-128-ecb",     | "2.16.840.1.101.3.4.1.2": "aes-128-cbc",     | "2.16.840.1.101.3.4.1.3": "aes-128-ofb",      @ ./~/parse-asn1/index.js 2:12-35  I tried to install primes, but Im getting  ERROR in ./~/diffie-hellman/lib/primes.json Module parse failed: /Users/kn/Documents/workbench/node_modules/diffie-hellman/lib/primes.json Unexpected token (2:11) You may need an appropriate loader to handle this file type. | { |     "modp1": { |         "gen": "02", |         "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"  @ ./~/diffie-hellman/browser.js 2:13-41  ERROR in ./~/elliptic/package.json Module parse failed: /Users/kn/Documents/workbench/node_modules/elliptic/package.json Unexpected token (2:9) You may need an appropriate loader to handle this file type. | { |   "_args": [ |     [ |       {  @ ./~/elliptic/lib/elliptic.js 5:19-45  ERROR in ./~/parse-asn1/aesid.json Module parse failed: /Users/kn/Documents/workbench/node_modules/parse-asn1/aesid.json Unexpected token (1:25) You may need an appropriate loader to handle this file type. | {"2.16.840.1.101.3.4.1.1": "aes-128-ecb", | "2.16.840.1.101.3.4.1.2": "aes-128-cbc", | "2.16.840.1.101.3.4.1.3": "aes-128-ofb",  @ ./~/parse-asn1/index.js 2:12-35 

Updating once again after changing the code inside main.js Suggestion from @marknadal did the trick

main.js

/**  * Main.js  */ 'use strict';  /**  * Setup Gun  * TODO: add peers  */ var Gun = require('gun/gun'); var peers = [     'http://localhost:8080/gun' ]; var gun = Gun(peers);  var React = require('react'); var ReactDom = require('react-dom');  var App = React.createClass({     render() {         return <div>Hello</div>     } });  var ROOT = document.getElementById('appmount');  ReactDom.render(     <App />,     ROOT ); 

And webpack.config

var path = require('path'),     webpack = require('webpack');  module.exports = {     devtool: 'source-map',     target: 'web',     node: {         fs: 'empty'     },     entry: {         workboard: './src/workboard/main.js'     },     output: {         path: __dirname, filename: '/public/[name]/js/bundle.js'     },     module: {         loaders: [             {                 test: /.js?$/,                 loader: 'babel-loader',                 exclude: /node_modules/,                 query: {                     presets: ['es2015', 'react', 'stage-2', 'stage-1']                 }             },             {                 test: /\.json$/,                 loader: 'json',                 include: [                         /node_modules/                     ]             }         ],         noParse: [/aws-sdk/]     },     plugins: [         new webpack.DefinePlugin({ "global.GENTLY": false })     ] }; 

and package.json - it does include a lot more than what's needed for this project, disregard that if you want to attempt to get this running on your own

{   "name": "workbench",   "version": "1.0.0",   "description": "My local workbench",   "main": "index.js",   "scripts": {     "test": "echo \"Error: no test specified\" && exit 1",     "start": "cd public && serve"   },   "author": "kn@unisport.dk",   "license": "ISC",   "dependencies": {     "babel-core": "^6.7.7",     "babel-preset-stage-1": "^6.5.0",     "babel-preset-stage-2": "^6.5.0",     "express": "^4.14.0",     "fetch": "^1.0.1",     "react": "^0.14.8",     "react-dom": "^0.14.8",     "react-router": "^2.3.0"   },   "devDependencies": {     "babel-core": "^6.5.2",     "babel-loader": "^6.2.4",     "babel-preset-es2015": "^6.5.0",     "babel-preset-react": "^6.5.0",     "bufferutil": "^1.2.1",     "gun": "^0.3.992",     "json-loader": "^0.5.4",     "loader-utils": "^0.2.15",     "prime": "^0.5.0",     "primes": "0.0.1",     "tls": "0.0.1",     "url": "^0.11.0",     "utf-8-validate": "^1.2.1",     "webpack": "^2.1.0-beta.5"   } } 

Now when I use webpack --watch no warnings or errors are shown. Going to public/workboad and running serve, I see the react application running with no errors

回答1:

Did @riscarrott 's answer work? I'm the author of gun, and it looks like 1 of the errors is gun related. However I am not a webpack expert so I am unsure what is the problem.

I do know that require('gun') actually loads ./index.js that in turn loads server-side specific logic (which won't work in the browser). If riscarrott 's answer does not work, try replacing require('gun') with require('gun/gun') and see if it works. If this is the case, please file a bug report on https://github.com/amark/gun so we can get this fixed for future people.

If this did not help, several other people on the team and the community use webpack and gun a lot. I'll see if I can get them to reply here.

EDIT: It looks like the de facto way of other projects, like jquery/angular/etc. (https://www.npmjs.com/package/angular) is to have you include them with a < script > tag. Therefore we also recommend you do this as well, as it avoids all these build problems.

<script src="/node_modules/gun/gun.js"></script> 


回答2:

It looks like you're running your code in the browser but you're targeting 'node' so Webpack will leave require statements untouched when referencing builtin modules such as 'url'.

To fix this remove target: 'node'.



回答3:

My first instinct is maybe you can add a variable that can be detected at build time to maybe overcome the issues... on https://github.com/petehunt/webpack-howto section 6 (I know there's ways to define like 'ws' to not be pulled, because that will be provided by the browser target; I just don't see it on that page)

On my own project gun was failing to browserify, because of the optional require( 'ws' ) and other things, so I excluded it from packing, and just serve it directly. I also pulled require.js so I could require('gun') at a javascript level, just outside of the package and more in the application of the library-package.

Could also just fall back further to pulling gun using a script tag...



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!