How to set the module name or path used in require() calls of a module in browserify?

喜欢而已 提交于 2019-12-11 05:56:19

问题


I am using browserify to move a reusable typescript module into the browser using gulp.

gulp.task("default", function(){
return browserify({
                        basedir: '.',
                        debug: true,
                        require: ['./src/common/common.ts'],
                        fullPaths: false,
                        cache: {},
                        packageCache: {}
                    }).plugin(tsify)
    .bundle()
    .pipe(source('common.js'))
    .pipe(gulp.dest("dist"));
});

To my surprise I need to include the resulting common.js file via

require("c:\\Users\\Luz\\Desktop\\tstest\\client\\src\\common\\common.ts");

In typescript or in builds using UMD + require JS I require files using relative paths without problems with exactly the same code. In the moment I add browserify I get absolute paths. I tried compiling typescript myself and use browserify without tsify but it always demands an absolute path to include it. All other modules that require common.js will fail to find it. How can I fix this?

Edit: Example how it looks like in the html file:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <script src="common.js"></script>
    </head>
    <body>
        <script>
            console.log("script started");

            //works
            var test = require("c:\\Users\\Luz\\Desktop\\tstest\\client\\src\\common\\common.ts");
            test.printCommon();

            //fails (all other modules will try to find it at this path)
            var test2 = require("../common/common");
            test2.printCommon();
        </script>
    </body>
</html>

回答1:


While I couldn't find the root of the problem I found a solution that works:

var brofy = browserify({
                        basedir: '.',
                        debug: true
                    });
    brofy.plugin(tsify);
    brofy.require("./src/common/common.ts", { expose: "../common/common" });
    brofy.bundle()
    .pipe(source('common.js'))
    .pipe(gulp.dest("dist"));

The property expose will make sure that require("../common/common") leads to the correct module avoiding any absolute paths and allowing me to use the same paths I use in typescript.

Other bundles can reference the bundle using "brofy.external("../common/common");" to tell browserify to not include it in their own bundle and rather use require to find it.

Edit: Still hoping someone comes up with a better solution.



来源:https://stackoverflow.com/questions/38891391/how-to-set-the-module-name-or-path-used-in-require-calls-of-a-module-in-browse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!