Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Uncaught ReferenceError: require is not defined" with Angular 2/webpack

I am working an HTML template from a graphic design company into my Angular 2 project using node and webpack.

The HTML pulls in various scripts like this:

<script src="js/jquery.icheck.min.js"></script>
<script src="js/waypoints.min.js"></script>

so I am requiring them in my component.ts:

var icheckJs = require('../js/jquery.icheck.min');
var waypointsJs = require('../js/waypoints.min');

There are several other scripts too and some SASS which appears to be working correctly.

webpack is happy and build it all and an 'npm start' is successful too. However, when it reaches the browser, I get this complaint:

Uncaught ReferenceError: require is not defined node_modules/angular2/platform/browser.js:1 Uncaught ReferenceError: require is not defined

which is actually thrown by this line from url.js:

var punycode = require('punycode');

Is this a CommonJs require? I hadn't used this in web development before a few weeks ago so I'm still untangling the various requires from webback, CommonJs et at.

An extract from my webpack.config.js for the .js loader looks like this:

{ test: /\.js$/, loader: 'script' }

How do I work around this error?

like image 226
serlingpa Avatar asked Dec 23 '15 12:12

serlingpa


2 Answers

WebPack can do this alone. You need to make sure you load the initial chunk first using a script src tag. It will typically be the value of the entry: key in the WebPack config with -bundle appended. If you're not doing explicit chunking, your entry chunk should be both an initial and entry chunk and have the WebPack runtime in it. The WebPack runtime contains and loads the require function before your code runs.

Your components or whatever you're requiring need to be required from the entry file since your scripts will start there. Basically, if you're not explicitly chunking, the entry point JS file is the only one you can include with script src. Everything else needs to be required from it. What you include will typically have bundle in the JS filename. By default, it should be main-bundle.js.

like image 98
Mark H. Avatar answered Sep 25 '22 13:09

Mark H.


For anyone that is looking for an answer but the above doesn't work:

Short

Add or Replace current target in webpack.config.js to target: 'web'

A bit longer

Webpack has different targets, if you've experimented with this and changed your target to node it will use 'require' to load chuncks. The best thing is to make your target (or to add) target: 'web' in your webpack.config.js. This is the default target and loads your chuncks in a way the browser can handle.

I eventually found this solution here.

like image 21
Maniflames Avatar answered Sep 22 '22 13:09

Maniflames