Gulp - 在组合的 js 文件中使用 ES6 模块?

标签 gulp ecmascript-6 browserify babeljs

我正在尝试在当前的 GULP 设置中使用 ES6 模块。我读到浏览器或 Babel 尚不支持此功能,因此需要对 make this work 进行一些精心设置。 ,使用诸如 Browserifybabelifyvinyl-source-stream 之类的东西。 (似乎非常复杂的设置)。

我想要的与我在网上找到的示例不同。所有的例子都是导入外部文件,我真的不想要那样。我希望将所有文件捆绑到一个单个文件中,所有模块都已经存在。这是我拥有的:

我当前的 GULP 设置是这样的:

gulp.task('buildJS', function() {
    var src = [
        './js/dist/app.js',
        './js/dist/templates.js',
        './js/dist/connect.js',
        './js/dist/config.js',
        './js/dist/utilities.js',
        './js/dist/components/*.js',
        './js/dist/pages/**/*.js',
        './js/dist/modals/*.js',
        './js/dist/init.js' // must be last
    ];

    gulp.src(src)
        .pipe(concat('app.js'))
        .pipe(babel({modules:"common"})) // I have no idea what "modules" actually does
        .pipe(gulp.dest('../js/'))

});

这是/js/dist/components/中组件文件的示例。
有很多这样的文件,它们都组合成一个文件。

module "components/foo" {
    export function render(settings) {
        return ...
    }
}

所以稍后我会在某些页面 Controller 中使用它:

import { render } from "components/foo";

问题:

现在我有了一个文件(已使用 Babel 转换),如何通过 Import 使用模块?

最佳答案

不,不要天真地连接文件。使用 browserify 来捆绑它们,使用 babelify 来编译它们(通过 babel)。一个基本示例如下所示:

browserify('./entry')
  .transform(babelify)
  .bundle()
  // ...

很难给出更具体的建议,因为您的用例非常不清楚。您是否有一个从一个文件开始的依赖关系图,或者您是否试图将一堆独立的模块捆绑在一起?您是要尝试运行脚本来启动应用程序,还是只想能够单独访问模块?

根据您在评论中链接到的示例,您应该有这样的内容:

components/doughnut.js

export default function Doughnut (settings = {}) {
  // ...
};

Doughnut.prototype = {}

routes/home.js

import Doughnut from './components/doughnut';
export default function () {
  var component = new Doughnut();
  $('body').html(component.render());
};

让每个模块导出您希望从任何其他模块获得的内容。让每个模块从任何其他模块导入任何它需要的东西。无论使用此示例中的 Controller ,都应该执行 import home from './routes/home';这些模块未绑定(bind)到全局变量 App 并且可以在其他应用程序中重复使用(只要您以其他方式使它们可重复使用)。

.pipe(babel({modules:"common"})) // I have no idea what "modules" 

modules 是一个 babel option 这决定了它把 ES6 模块语法编译成什么模块格式。在这种情况下,CommonJS。

module "components/foo" {

感谢您的评论,我现在明白您为什么要这样做了。你需要消除它。您的组件文件应该类似于:

export function render (settings) {
    return ...
}

配对:

import { render } from "components/foo";

或者如果您想要默认导出/导入:

export default function render (settings) {
    return ...
}
import render from "components/foo";
import { render } from "components/foo";

如果你正在浏览你的模块,你可能需要使用像 ./components/foo 这样的相对路径或者使用其他东西来处理路径,像 babel 的 resolveModuleSource 选项。

关于Gulp - 在组合的 js 文件中使用 ES6 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33065014/

相关文章:

javascript - gulp 部分转编译

javascript - 使用 gulp-eslint 的问题

javascript - 在 JavaScript 中从没有 BST 的时间戳格式化日期

javascript - 实现 Object.seal、Object.freeze、Object.preventExtensions 的替代方案

javascript - 如何在 gulp 中创建重复管道?

javascript - 在 Browserify 和 NPM 中需要根路径(在这两个地方都去掉 '../../../..')

javascript - JS reducer : return combined array of objects

javascript - Browserify独立选项不直接包装指定名称的代码?

javascript - 捆绑的 Webextension 看不到 JQuery

javascript - 需要 highcharts-browserify 才能使用特定版本的 highcharts?