将ES6表达的节点文件打包到单个节点模块中

时间:2016-06-01 06:34:04

标签: node.js grunt-browserify grunt-babel

我有一组相互依赖的Node.js模块,我一直在构建为ES6模块,理想情况下我希望能够将单个模块指定为入口点,并将这些模块构建(使用grunt)到单个模块中Node应用程序可能需要的文件。

grunt-babel似乎无法处理这种包装。

我知道浏览器可以为浏览器执行此操作,我知道browserify可以包含节点模块,但我无法弄清楚如何让browserify将单个模块入口点转换为需要的节点模块

因此,如果我的源文件(和入口点),src/hello.js是:

import world from './world.js';
export default function () {console.log('Hello' + world + '!');};

src/world.js是:

export default 'world';

我希望能够从普通的Node应用程序中使用它,例如:

var hw = require('./dest/hello-world.js');
hw();

我的grunt文件需要看起来像什么?

1 个答案:

答案 0 :(得分:0)

原来我有两个问题:

在我需要的.babelrc文件中:

{
  "presets": ["es2015"],
  "plugins": ["add-module-exports"]
}

...而在我需要的Grunt文件中:

    browserify: {
        myNode: {
            options: {
                transform: [['babelify', {sourceMaps: true}]],
                browserifyOptions: {
                    standalone: 'dummyPlaceholder'
                }
                // Depending on your needs, you may also
                //  need `node: true` here or the options
                // in the 2nd argument of the `browserify` call
                // (as I required to allow GLOBAL.window = GLOBAL
                //  injection)
                // at https://github.com/substack/node-browserify/issues/1277#issuecomment-115198436
            },
            files: {
                'dist/<%= pkg.name%>-node.js': 'src/node.js'
            }
        }
    },

插件"add-module-exports"是必要的,以避免Babel发生变化,这需要var mod = require('mod').default;之类的呼叫,而不仅仅是var mod = require('mod');

standalone属性实际上并不用于创建全局,因为它在模块环境(Node / CommonJS)中使用,但是属性的存在是触发导出所必需的。 / p>

相关问题