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

时间:2015-10-11 12:34:57

标签: gulp ecmascript-6 browserify babeljs

我正在尝试在当前的GULP设置中使用ES6模块。我已经读过浏览器或Babel尚未支持此功能,因此需要对make this work进行一些精心设置,使用Browserifybabelify,{{1}等内容}。 (似乎极其复杂的设置)。

我想要的东西与我在网上找到的例子不同。所有示例都是导入外部文件,我真的不希望这样。我希望将所有文件捆绑到单个文件中,其中包含所有模块。这就是我所拥有的:

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

vinyl-source-stream

这是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 ...
    }
}

问题:

现在我有一个文件(使用Babel进行转换),如何通过import { render } from "components/foo"; 使用模块?

2 个答案:

答案 0 :(得分:1)

不,不要天真地连接文件。使用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());
};

让每个模块从任何其他模块导出您想要的内容。让每个模块从任何其他模块导入所需的任何内容。无论使用此示例中的控制器,都应执行import home from './routes/home';这些模块不依赖于全局变量App,可以在其他应用程序中重用(只要您将它们重复使用)。

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

modulesbabel 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选项。

答案 1 :(得分:0)

自2015年底以来,我一直在使用rollupjs来创建一个ES2015(ES6)模块包,因此我可以在代码中自由使用 import / export 。 / p>

  

我发现Rollupjs非常好用且易于使用。背后的人   是伟大的人民,他们致力于这个项目。我有过   我在项目的Github问题页面上发布了很多问题   我总能很快得到答复。

安装程序包含以下rollupjs插件:

  1. rollup(基本rollupjs bundler)
  2. rollup-plugin-babel(将旧版浏览器支持的ES2015代码转换为ES5或更早版本)
  3. rollup-plugin-eslint(验证javascript代码是否有效)
  4. rollup-plugin-uglify(缩小代码,缩小代码)
  5. rollup-plugin-progress(显示终端中的捆绑进度。显示正在"正在处理的文件")
  6. beepbeep(发出控制台发出哔哔声。我用它来告诉我编译错误)
  7. 简化 GULP 设置我使用:

    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'});
    });
    
相关问题