问题描述
这是将我的ES6代码编译成单个ES5文件的gulp任务。我在ES6中使用类和模块( import
, export
)。
$ b $
$ b $ ['es2015']
}))
.pipe(concat('all.js'))
.pipe(sourcemaps.write('。'))
.pipe (gulp.dest( ./ WWW / JS'));
但是,因为Babel编译ES6 import
进入需要
命令,需要
将尝试请求一个文件,因为所有ES5代码都是请求文件失败连接成一个文件all.js.
结果是一堆错误:找不到模块的错误。如何将它们全部保存在单个文件中的模块可以编译?
你不是第一个需要使用Babel将JSX / ES6传播到ES5,但不使用CommonJS模块,因此Browserify / Webpack。不幸的是,当时不可能(,,),看起来似乎是不可能的。如果您想使用与Babel一同使用的ES6,您几乎不得不使用这些工具,但是您不会有机会使用其他连接/内联JavaScript(因为所有这些 require()
调用而不是窗口
上的全局变量)。可惜,Babel不允许改变这种行为。
Here's my gulp task to compile my ES6 code into a single ES5 file. I use classes and modules (import
, export
) in ES6.
gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015']
}))
.pipe(concat('all.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./www/js'));
However, because Babel compiles ES6 import
directives into require
commands, and require
will attempt to request a file, the request files are failing because all the ES5 code is concatted into one file, all.js.
The result is a bunch of "Error: Cannot find module" errors. How can I compile modules that work when they're all saved in a single file?
You're not the first one with the need of transpiling JSX/ES6 to ES5 with Babel but without using CommonJS modules and hence Browserify/Webpack. Unfortunately it turns out this is not possible at the time (1, 2, 3), and it looks like it won't be possible ever. You're pretty much forced to use these tools if you want to use ES6 transpiled with Babel, but you won't have the chance to use the resulting code with other concatenated/inline JavaScript (because of all those require()
calls rather than global variables on window
). It's a pity Babel doesn't allow to change this behaviour.
这篇关于使用Babel与单个输出文件和ES6模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!