E
E
Evgeny Simonenko2016-02-06 13:15:55
JavaScript
Evgeny Simonenko, 2016-02-06 13:15:55

How to make a bundle using browserify without including external modules that will be loaded from the CDN?

As you know, by default, when creating a bundle, browserify also includes third-party modules from NPM. But I would like these modules to be loaded from the CDN, and only my own code in the bundle. Tried options for browserify: exclude, external, ignore. But all this led to the fact that third-party modules were not found. Below is the html code:

<!doctype html>

<html>
  <head>
    <meta charset="utf-8"/>
    <title></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.min.js"></script>
  </head>
  <body>
    <div id="app">
      <p style="color: darkred;">JavaScript is not allowed either in the app error.</p>
    </div>
    <script src="app.js"></script>
  </body>
</html>

gulpfile.js code snippet:
gulp.task('bundle', ['compile'], () => {
  //var b = browserify('build/spa/Main.js', {bundleExternal: false});
  var b = browserify('build/spa/Main.js');
  b
    //.ignore('react')
    //.ignore('react-dom')
    .bundle()
    .pipe(source('app.js'))
    .pipe(gulp.dest('dist'));
  gulp
    .src('src/spa/index.html')
    .pipe(gulp.dest('dist'));
});

UPD1. I think it needs to be added. The JavaScript code is the result of compiling TypeScript code with the module: commonjs option. In the JavaScript code, require() calls appear after compilation. So, if the code of third-party modules is not included in the bundle, then this call to require () fails. Same story with other types of modules.
UPD2. The problem was solved by myself. See below.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Simonenko, 2016-02-06
@easimonenko

So, my solution to the problem, found after a break for physical education and subsequent re-reading of the README of the browserify-shim package: Install the browserify-shim
module:
Add the following lines to the package.json of the project:

"browserify": {
    "transform": ["browserify-shim"]
  },
  "browserify-shim": {
    "react": "global:React",
    "react-dom": "global:ReactDOM"
  }

In gulpfile.js, replace the line:
with the line:
We start rebuilding the application, and voila, everything works! :-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question