我想开始使用 ES6,我想用 grunt 来管理我的文件。到目前为止,这是我的项目结构:
Gruntfile.js
package.json
dist/
src/
index.es6
这就是
index.es6
好像:import MapGL from 'react-map-gl';
const data = [];
const viewport = new Viewport();
这些包都定义在
package.json
并安装。如何将此 ES6 文件转换为 ES5 JavaScript?是的,我可以将它转换为某种 JavaScript,但它没有转换
require
声明。这是我当前的 Gruntfile:
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';'
},
dist: {
src: ['src/**/*.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
},
jshint: {
files: ['src/index.js', 'test/index.js'],
options: {
reporterOutput: '',
esnext: true,
globals: {
console: true,
module: true,
document: true
}
}
},
babel: {
files: {
expand: true,
src: ['src/*.es6'],
ext: '-compiled.js'
},
options: {
sourceMap: true,
presets: ['babel-preset-es2015']
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['babel', 'jshint', 'concat']
}
});
grunt.registerTask('default', ['babel', 'jshint', 'concat', 'uglify']);
};
运行
grunt
生成以下文件:Gruntfile.js
package.json
dist/
myproject.js
src/
index.es6
index-compiled.js
index-compiled.map
但是
myproject.js
包含行 var _reactMapGl = require('react-map-gl');
在浏览器中失败。
最佳答案
是的,根据 @Matthew Herbst推荐,Browserify将处理 import
ES6 模块的绑定(bind)。还有一个名为 babelify 的包将有助于处理您的 babel browserify 转换。
以下似乎运作良好:
使用babel-cli
而不是 babel
.
因此,首先,从您的
package.json
中删除/卸载它。 (如果存在!):$ npm uninstall babel --save-dev
...并卸载 grunt-babel :
$ npm uninstall grunt-babel --save-dev
$ npm install --save-dev babel-cli babel-preset-es2015
{
"presets": ["es2015"]
}
grunt-browserify
package.json
:$ npm install grunt-browserify --save-dev
babelify
$ npm install babelify --save-dev
Gruntfile.js
Gruntfile.js
由 删除 现有的babel
任务: // DELETE the following...
babel: {
files: {
expand: true,
src: ['src/*.es6'],
ext: '-compiled.js'
},
options: {
sourceMap: true,
presets: ['babel-preset-es2015']
}
},
browserify
代替任务: browserify: {
dist: {
files: {
// destination for transpiled js : source js
'dist/myproject.js': 'src/index.es6'
},
options: {
transform: [['babelify', { presets: "es2015" }]],
browserifyOptions: {
debug: true
}
}
}
}
您可能还需要更新和更改传递给
grunt.registerTask
的数组中任务的顺序。 .对此:grunt.registerTask('default', [
'jshint',
//'concat', <-- Probably don't need to concat the files, assuming index.es6 imports the necessary modules.
'browserify:dist',
'uglify'
]);
附加说明:
使用 react presets 可能有一些好处除了es2015 presets - 这将需要相应地修改上面的第 2、3 和 7 点,但是,我自己没有使用它。
希望这可以帮助!
关于javascript - 使用 Babel + grunt 与 ES6 一起工作 - 如何转换 require 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41067220/