【问题标题】:How to set the module name or path used in require() calls of a module in browserify?如何在 browserify 中设置模块的 require() 调用中使用的模块名称或路径?
【发布时间】:2016-12-17 21:35:02
【问题描述】:

我正在使用 browserify 通过 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"));
});

令我惊讶的是,我需要通过

包含生成的 common.js 文件
require("c:\\Users\\Luz\\Desktop\\tstest\\client\\src\\common\\common.ts");

在 typescript 或使用 UMD + require JS 的构建中,我需要使用相对路径的文件,而代码完全相同。在我添加 browserify 的那一刻,我得到了绝对路径。我尝试自己编译 typescript 并在没有 tsify 的情况下使用 browserify,但它总是需要一个绝对路径来包含它。所有其他需要 common.js 的模块都将找不到它。我该如何解决这个问题?

编辑:示例在 html 文件中的外观:

<!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>

【问题讨论】:

    标签: browserify tsify


    【解决方案1】:

    虽然我找不到问题的根源,但我找到了一个可行的解决方案:

    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"));
    

    属性暴露将确保 require("../common/common") 导致正确的模块避免任何绝对路径,并允许我使用我在 typescript 中使用的相同路径。

    其他包可以使用 "brofy.external("../common/common");" 引用该包告诉 browserify 不要将它包含在他们自己的包中,而是使用 require 来查找它。

    编辑:仍然希望有人提出更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2021-12-08
      • 1970-01-01
      • 2012-10-30
      相关资源
      最近更新 更多