简体   繁体   English

如何连接 ES6 模块?

[英]How do I concatenate ES6 modules?

How can I concatenate ES6 modules?如何连接 ES6 模块?

var foo = 2; // This would normally be scoped to the module.
export function Bar() {}

// ...concatenate...

import { Bar } from 'javascripts/bar' //This file no longer exists in the concatenated scenario.
export function Bam() {}

Update 2020-09-02: Esperanto was replaced by Rollup some time ago, and is a great choice for this problem. 2020-09-02 更新:前段时间世界语被Rollup取代,是这个问题的绝佳选择。 Depending on your needs, Webpack may also be a good choice.根据您的需求, Webpack也可能是一个不错的选择。


If what you want to do is create a single JavaScript file that does not internally use ES6 modules, so that you can use it with browsers/node today, then I recommend using Esperanto (full disclosure, I'm a maintainer of the project).如果您想做的是创建一个内部不使用 ES6 模块的 JavaScript 文件,以便您今天可以在浏览器/节点中使用它,那么我建议使用世界语(完全公开,我是该项目的维护者) . It allows you to create a bundle that concatenates all of the files together without the use of a loader like you'd get using something like browserify or webpack.它允许您创建一个将所有文件连接在一起的包,而无需像使用 browserify 或 webpack 那样使用加载程序。 This typically results in smaller code (no loader), better dead code elimination (when using a minifier like Google Closure Compiler or UglifyJS), and better performance as the JS interpreter is better able to optimize the result.这通常会产生更小的代码(无加载器),更好地消除死代码(当使用像 Google Closure Compiler 或 UglifyJS 这样的压缩器时),以及更好的性能,因为 JS 解释器能够更好地优化结果。

Here's an example usage, but note that there are plenty of tools to integrate Esperanto into your workflow :这是一个示例用法,但请注意,有很多工具可以将世界语集成到您的工作流程中

var fs = require( 'fs' );
var esperanto = require( 'esperanto' );

esperanto.bundle({
  base: 'src', // optional, defaults to current dir
  entry: 'mean.js' // the '.js' is optional
}).then( function ( bundle ) {
  var cjs = bundle.toCjs();
  fs.writeFile( 'dist/mean.js', cjs.code );
});

This example is taken from the wiki page on bundling ES6 modules .此示例取自有关捆绑 ES6 模块wiki 页面

I would suggest that you take a look at http://webpack.github.io and then combine it with babel.我建议您查看http://webpack.github.io ,然后将其与 babel 结合使用。

alternatively you can do it with babel alone:或者,您可以单独使用 babel 来完成:

https://babeljs.io/docs/usage/cli/ https://babeljs.io/docs/usage/cli/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM