Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

javascript - Concatenate files using babel

Here's my file structure

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

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

include 'base.js'

/foo/bar/main.js

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

/baz/main.js

include 'base.js'

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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).

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 

(or use a .babelrc file)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...