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

Gulp 在组合js文件中使用ES6模块?,gulp,ecmascript-6,browserify,babeljs,Gulp,Ecmascript 6,Browserify,Babeljs,我正在尝试在当前的GULP设置中使用ES6模块。我已经了解到浏览器或Babel还不支持这一点,因此需要一些精心的设置,使用Browserify,babelify,乙烯基源流。(设置似乎非常复杂) 我想要的与我在网上找到的例子不同。所有的例子都是导入外部文件,我真的不希望这样。我希望将所有文件捆绑到一个文件中,所有模块都已存在。以下是我所拥有的: 我当前的吞咽设置如下所示: gulp.task('buildJS', function() { var src = [ './j

我正在尝试在当前的GULP设置中使用ES6模块。我已经了解到浏览器或Babel还不支持这一点,因此需要一些精心的设置,使用
Browserify
babelify
乙烯基源流
。(设置似乎非常复杂)

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

我当前的吞咽设置如下所示:

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 ...
    }
}
因此,稍后在某个页面控制器中,我将使用它:

import { render } from "components/foo";

问题:
现在我有了一个文件(使用Babel进行了转换),如何通过
Import
使用模块

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

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/'))

});
browserify(“./entry”)
.变换(babelify)
.bundle()
// ...
很难给出更具体的建议,因为您的用例太不清楚了。您是否有一个从一个文件开始的依赖关系图,或者您正在尝试将一组独立的模块捆绑在一起?您是在尝试运行脚本启动应用程序,还是只希望能够单独访问模块

根据您在评论中链接的示例,您应该有如下内容:

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/'))

});
components/doughnut.js

导出默认函数甜甜圈(设置={}){
// ...
};
Doughnut.prototype={}
routes/home.js

从“./components/Doughnut”导入甜甜圈;
导出默认函数(){
var component=新的甜甜圈();
$('body').html(component.render());
};
让每个模块导出您希望从任何其他模块获得的内容。让每个模块从任何其他模块导入所需的任何内容。无论使用本例中的控制器的是什么,都应该执行
从“/routes/home”导入home'
;这些模块不绑定到全局变量
App
,可以在其他应用程序中重用(只要您以其他方式使其可重用)

modules
是一个用于确定将ES6模块语法编译为何种模块格式的函数。在本例中,CommonJS

多亏了你的评论,我现在才明白你为什么要这样做。你需要消除这一点。您的组件文件应类似于:

导出函数渲染(设置){
返回。。。
}
搭配:

从“组件/foo”导入{render};
或者,如果需要默认的导出/导入:

导出默认函数渲染(设置){
返回。。。
}
从“组件/foo”导入渲染;

如果您正在浏览模块,您可能需要使用相对路径,如
/components/foo
,或者使用其他方法来处理这些路径,如babel的
resolveModuleSource
选项。

自2015年底以来,我一直在使用它来创建一批ES2015(ES6)模块,因此,我可以在代码中自由使用导入/导出


我发现Rollupjs非常好用。背后的人 是伟大的人献身于这个项目。我有 我在项目的Github问题页面上发布了许多问题 我总是很快得到答复


安装程序包括以下rollupjs插件:
  • (基本rollupjs捆绑机)
  • (将ES2015代码转换为ES5或更早版本,以支持传统浏览器)
  • (验证javascript代码是否有效)
  • (缩小代码,使其更小)
  • (显示终端中的捆绑进度。显示正在“处理”的文件)
  • (发出控制台嘟嘟声。我用它来通知我操作错误)

  • 我正在使用的简化吞咽设置:
    我假设您想在浏览器中导入一个模块,对吗?不在node@pilau-是的浏览器,只有在浏览器中才发现最好的方法是使用一些代码“启动”一切,是的。基本上,有一些js文件是页面的“控制器”,它们使用诸如“header”、“breadcrumbs”之类的模块(控制器)。。我想把所有这些控制器转换成ES6模块。目前,他们正在“驾驭”应用程序名称空间:
    App.components.breadcrumbs=function(){…
    我想把它们转换成独立的模块,比如。所有的文件,我的意思是所有的,都被合并成一个,所以一旦加载DOM,所有的东西都可以从任何地方访问。我认为这是ES6导入。从一些方面看,他似乎成功了。不,不是。在教程中你在哪里看到类似
    模块“components/foo”的东西 {
    ?我在页面中根本找不到
    module
    这个词。ES6模块语法都是关于
    import
    export
    声明的。哈,我以为注释是指向它后面的内容,而不是之前的内容。我误解了你的意思。我想我应该从它们明确使用“模块…”一词啊,我明白了。出于这个原因,我曾考虑过使用要点,但似乎不值得这么麻烦。您刚刚发布的链接似乎是两年前的链接。最终的ES6规范仅在几个月前发布。无论如何,如果该构造的目的是支持连接,那么在使用browserify进行捆绑时就无关紧要了。
    import { render } from "components/foo";
    
    var gulp               = require('gulp'),
        gutil              = require('gulp-util'),
        rollup             = require('rollup').rollup,
        babelRollup        = require('rollup-plugin-babel'),
        eslintRollup       = require('rollup-plugin-eslint'),
        uglifyRollup       = require('rollup-plugin-uglify'),
        rollupProgress     = require('rollup-plugin-progress'),
        beep               = require('beepbeep');
    
    // ESlint 
    var eslint_settings = {
        rulePaths: [],
        rules: {
            "no-mixed-spaces-and-tabs" : [2, "smart-tabs"],
            "block-spacing"            : [2, "always"],
            "comma-style"              : [2, "last"],
            "no-debugger"              : [1],
            "no-alert"                 : [2],
            "indent-legacy"            : [1, 4, {"SwitchCase":1}],
            'strict'                   : 0,
            'no-undef'                 : 1
        },
        ecmaFeatures : {
            modules: true,
            sourceType: "module"
        },
        "parserOptions": {
            "ecmaVersion" : 6,
            "sourceType": "module",
            "ecmaFeatures": {
                "jsx": false,
                "experimentalObjectRestSpread": true
            }
        },
        globals : ['$', '_', 'afterEach', 'assert', 'beforeEach', 'Cookies', 'd3', 'dataLayer', 'describe', 'done', 'expect', 'ga', 'it', 'jQuery', 'sinon'], baseConfig: {
            //parser: 'babel-eslint',
        },
        envs: [
            'browser', 'es6'
        ]
    };
    
    
    // Rollup plugins configuration
    function getRollupPlugins( settings = {} ){
        var rollupPlugins = [];
    
        rollupPlugins.push({
            presets        : [['es2015', {"modules": false}]], //['es2015-rollup'],
            runtimeHelpers : true,
            exclude        : 'node_modules/**',
            plugins        : ["external-helpers"]
        });
    
        rollupPlugins.push(eslintRollup( Object.assign({throwOnError:true}, eslint_settings) ))
    
        rollupPlugins.push(rollupProgress({
             clearLine:true // default: true
        }))
    
        // I would advise Babel to only be used for production output since it greatly slower bundle creation
        if( settings.ENV == 'production' ){
            rollupPlugins.push(uglifyRollup())
            rollupPlugins.push(babelRollup(rollupPlugins__babel));
        }
    
        return rollupPlugins;
    }
    
    var rollupPlugins = getRollupPlugins();
    
    /**
     * a generic Rollup bundle creator
     * @param  {String} outputPath     [where to save the bundle to (must end with /)]
     * @param  {String} outputFileName [bundle file name]
     * @param  {String} entryFile      [rollup entry file to start scanning from]
     * @return {Object}                [Promise]
     */
    function rollupBundle(outputPath, outputFileName, entryFile, bundleOptions){
        bundleOptions = bundleOptions || {};
        bundleOptions.plugins = bundleOptions.plugins || rollupPlugins;
    
        return new Promise(function(resolve, reject) {
            outputFileName += '.js';
            var cache;
    
            // fs.truncate(outputPath + outputFileName, 0, function() {
            //     gutil.log( gutil.colors.dim.gray('Emptied: '+ outputPath + outputFileName) );
            // });
    
            rollup({
                entry   : entryFile,
                plugins : bundleOptions.plugins,
                cache   : cache
            })
            .then(function (bundle) {
                var bundleSettings = {
                        format    : bundleOptions.format || 'umd',
                        sourceMap : false,
                        banner    : config.banner
                    },
                    result = bundle.generate(bundleSettings),
                    mapFileName = outputFileName + '.map',
                    sourceMappingURL = '\n//# sourceMappingURL='+ mapFileName;
    
                cache = bundle;
    
                // if folder does not exists, create it
                if( !fs.existsSync(outputPath) ){
                    gutil.log( gutil.colors.black.bgWhite('Creating directory ' + outputPath) );
                    fs.mkdirSync(outputPath);
                }
    
                // save bundle file to disk
                fs.writeFile( outputPath + outputFileName, result.code + (bundleSettings.sourceMap ? sourceMappingURL : ''), function(){
                    resolve();
                });
    
                // save map file to disk
                if( bundleSettings.sourceMap )
                    fs.writeFile( outputPath + mapFileName, result.map.toString());
            })
            .catch(function(err){
                beep(1);
                gutil.log( gutil.colors.white.bgRed('Rollup [catch]: ', err.stack) );
                resolve();
            })
        });
    }
    
    // This task bundles the main application, using an entry file which itself has many imports, 
    // and those imports also has imports.. like a tree branching
    gulp.task('bundle-app', ()=>{
        return rollupBundle('../dist/js/', 'app', 'js/dist/app.js', {format:'cjs'});
    });