browserify require in required file cannot find mo

2019-03-01 11:53发布

问题:

I'm trying to package my angular js into a single script using browserify. It works well when I use require from within my main file app.js, but when one of the modules required in app.js contains it's own require, the dependency is not included in my bundle.

To recap, in app.js (link to line in repo):

require("splash-header");
// more code here

splashHeader.js:

require("social-button-directive");
// more code here

socialButtons.js has no dependencies.

browserify --list app.js does not list splashHeader.js as it should, and the bundle produced via browserify app.js -o bundle.js does not include socialButton's javascript. So of course if I attempt to load the site anyway, I get Uncaught Error: Cannot find module 'social-button-directive' at splashHeader's require('social-button-directive').

Also important to note that I'm mapping module names to file locations using the "browser" option in package.json, and using browerify-shim since none of my modules are common-js compatible.

relevant section of package.json:

"dependencies": {
    "browserify": "~9.0.3",
    "browserify-shim": "~3.8.3"
},
"browserify": {
    "transform": [
        "browserify-shim"
    ]
},
"browserify-shim": {
    "splash-header": {
        "depends": "angular",
        "exports": "angular.module('splash-header').name"
    },
    "social-button-directive": {
        "depends": "angular",
        "exports": "angular.module('social-button-directive').name"
    }
},
"browser":{
    "splash-header": "./ng-modules/splashHeader/splashHeader.js",
    "social-button-directive": "./ng-modules/socialButtons/socialButtons.js"
}

I've been on this all morning and am completely stumped. I've cut down the offending project to serve as a minimal example of the issue. To test things out just clone and npm install. If you're looking in detail, here's the working/not working version diff.

I've tried loading the submodule by relative path (require('./ng-modules/socialButtons/socialButtons.js)`), no luck. Perhaps I have shimmed things incorrectly? My approach on this comes from this article.

EDIT: It is most certainly my browserify-shim configuration. Everything works after converting the modules to commonjs and removing the browserfy-shim options from package.json. I guess I just had to write this all out to pin it down. =/