Defining global variable for Browserify

前端 未结 2 650
甜味超标
甜味超标 2020-12-01 10:46

I\'m using SpineJS (which exports a commonjs module) and it needs to be available globally because I use it everywhere, but It seems like I have to do Spine = require(

2条回答
  •  心在旅途
    2020-12-01 10:55

    First of all, for your example David is correct. Include all dependencies in every module you need it in. It's very verbose, but there is no compile time magic going on which alleviates all sorts of anti patterns and potential future problems.

    The real answer.

    This isn't always practical. Browserify accepts an option called insertGlobalVars. On build, each streamed file is scanned for identifiers matching the key names provided and wraps the module in an IIFE containing arguments that resolve each identifier that is not assigned within the module. This all happens before the dependency tree is finalized, which allows you to use require to resolve a dependency.

    TLDR

    Use insertGlobalVars option in Browserify.

    browserify({
      insertGlobalVars: {
        spine: function(file, dir) {
          return 'require("spine")';
        }
      }
    });
    

    For every file scanned, if an identifier spine exists that's not assigned, resolve as require("spine").

提交回复
热议问题