1

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

在打字稿或使用 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>
4

1 回答 1

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") 导致正确的模块避免任何绝对路径并允许我使用我在打字稿中使用的相同路径。

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

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

于 2016-08-11T22:41:45.477 回答