问题
I'm trying to use Babel in my grunt build process to transpile my .js
project files from ES6 to ES5. I have a watch
task watching my .js
directory for changes and when changes are detected, I run the babel
task.
For some reason though, changing just one .js
file takes anywhere between 6-10 seconds to complete. I have a feeling it's transpiling the entire project, but I'm not sure. My Gruntfile.js
looks like this:
grunt.initConfig({
watch: {
babel: {
files: ["<%= yeoman.app %>/scripts/**/*.js"],
tasks: ["babel"]
},
livereload: {
options: {
livereload: LIVERELOAD_PORT
},
files: [
"{.tmp,<%= yeoman.app %>}/scripts/**/*.js",
]
}
},
babel: {
options: {
sourceMap: true,
presets: ['es2015']
},
dist: {
files: [
{
expand: true,
cwd: '<%= yeoman.app %>/scripts/',
src: ['**/*.js'],
dest: '.tmp/scripts/'
}
]
}
}
});
grunt.registerTask("serve", function(target) {
return grunt.task.run(["watch"]);
});
When I run grunt serve
and change a file it logs the execution time:
Running "babel:dist" (babel) task
Done, without errors.
Execution Time (2015-12-01 11:57:54 UTC) babel:dist 6.7s ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100% Total 6.7s
But when I use babel-cli
in my terminal, it transpiles in milliseconds, almost instantaneously even:
babel --presets es2015 script.js --out-file transpiled.js
Surely this is way too long. Am I doing something wrong here.
Any help is appreciated. Thanks in advance!
回答1:
During development you can decide to run the JS version of the Babel-core directly in the browser, which runs quite fast.
Then for deployment you can make a specific Grunt build task that removes the Babel-Core from the HTML and instead transpiles the files with the Grunt Babel plugin.
Your Gruntfile will have something like this:
grunt.registerTask('build', ['processhtml', 'babel']);
grunt.registerTask('default', [''watch']);
For the removal of the Babel-core JS you can use plugins like like grunt-processhtml: http://www.npmjs.com/package/grunt-processhtml . The HTML will look like this:
<!-- build:remove -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
<!-- /build -->
The JS Babel-core can found here: http://cdnjs.com/libraries/babel-core . You can download it and add it to your project or just run it from the CDN directly.
来源:https://stackoverflow.com/questions/34019931/grunt-babel-taking-6-seconds-per-file