使用babel连接文件 [英] Concatenate files using babel

查看:67
本文介绍了使用babel连接文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的文件结构

/base.js
    /foo/main.js
        /foo/bar/main.js
    /baz/main.js

我总共要4个文件.树的每个叶节点一个,其中包含其包含"文件的所有内容.这是文件的内容.

I want 4 files in total. One for each leaf node of the tree with all the content of it's 'included' files. Here are file's contents.

base.js

//anything really

/foo/main.js

/foo/main.js

include 'base.js'

/foo/bar/main.js

/foo/bar/main.js

include 'base.js'
include '/foo/main.js'

/baz/main.js

/baz/main.js

include 'base.js'

这些包含"就像php包含一样,因为它们是在babel的编译时串联在一起的,而不是es2016/es2016中的传统包含.我想让每个文件都针对过去的ES版本进行babel编译,并在将其提供服务之前使它的所有内容都包含层次结构.它们将不在节点服务器上.这将是传统的php/apache托管.Babel只是为了传播目的.

These 'includes' are like php includes in that they are concatenated at babel's compile time not the traditional includes from es2016/es2016. I want to have each file be babel compiled for past versions of ES and have all the contents of it's include hierarchy before I put them up for serving. They will not be on a node server. This will be traditional php/apache hosting. Babel is just for transpiring purposes.

我知道我可以使用-out-file 选项将所有js编译到一个文件中,并且可以导入和导出模块,但是如何使babel连接不同的文件而无需编写并仅通过在文件顶部使用"include"指令来维护cli命令.

I know I can compile all my js in a single file with the --out-file option and I can import and export modules but how can I make babel concatenate different files without having to write and maintain cli command and just by having 'include' directives at the top of the files.

推荐答案

听起来您可以考虑使用浏览器,结合 babelify 将文件传输到ES5.

It sounds like you could consider using Browserify, combined with babelify to transpile the files to ES5.

基本上,要在树中捆绑所有"main.js"文件,可以运行以下命令(假设使用类似Unix的操作系统):

Basically, to bundle all "main.js" files in your tree, you could run the following (assuming a Unix-like OS):

for file in */**/main.js
do
  browserify -t [ babelify ] $file > $(dirname $file)/bundle.js
done

(您可以很容易地将其放入shell脚本中)

(you can put that in a shell script quite easily)

这将在 main.js 旁边创建一个名为 bundle.js 的文件,其中将包含 main.js 的转译内容,及其任何依赖项(您可以使用 require() import 加载).

This will create a file called bundle.js next to the main.js, which will include the transpiled contents of main.js, and any of its dependencies (which you load using require() or import).

要获取 babelify 将ES6转换为ES5,您需要安装一些常见的Babel预设,例如 es2015 ,并将它们作为参数传递给 babelify (请参见):

To get babelify to transpile ES6 to ES5, you need to install some common Babel presets like es2015, and pass them as argument to babelify (see this):

browserify -t [ babelify --presets [ es2015 ] ] $file 

(或使用 .babelrc 文件)

(or use a .babelrc file)

这篇关于使用babel连接文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆