M
M
miniven2018-03-07 09:58:45
JavaScript
miniven, 2018-03-07 09:58:45

How to set a global variable in Browserify?

I use Gulp + Browserify. There is such a task for building JS:

const scriptsServe = () => {
  const alias = [
    'all-page.js',
    'index-page.js'
  ];

  PATH.src.scripts.forEach((entry, index) => {
    const bundle = browserify({
      entries: entry
    });

    bundle.transform(babelify);
    bundle.bundle()
      .pipe(source(alias[index]))
      .pipe(gulp.dest(PATH.dest.scripts));
  });
};

And a little more in package.json:
"browserify-shim": {
    "jquery": "global:$"
  },
  "browserify": {
    "transform": [ "browserify-shim" ]
  }

Works well: two files are created. One of them for the main page, the other for all, including the main one. Both use plugins that require the jQuery library, unfortunately. So I would like to connect it as a separate file, which I did. But a problem arises: the $ and jQuery variables seem to be visible in both files, but for some reason Browserify still imports it into both of my files, even if I don’t write anywhere. As a result, the library is connected three times: once by an external script, once is imported into each of my js files. What am I doing wrong and how can I solve this problem? import $ from 'jquery';

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
miniven, 2018-03-07
@miniven

In general, the problem was solved by adding the following lines to gulpfile.js:
Replaced
with

bundle.transform(babelify, {
      global: true
    });
    bundle.transform("browserify-shim", {
      global: true
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question