2016-06-01 85 views
0

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

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

我知道browserify可以为浏览器做到这一点,我知道browserify可以包含节点模块,但我还没有弄清楚如何将browse模块转换为需要的节点模块。

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

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

src/world.js是:

export default 'world'; 

我想它能够从使用它正常的节点应用程序,如:

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

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

回答

0

原来我有两个问题:

在我.babelrc文件,我需要:

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

......而在我的咕噜声文件,我需要:

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"是必要的,以避免在巴贝尔需要调用像var mod = require('mod').default;,而不是只有var mod = require('mod');

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