javascript 带有 Gulp 的 ES6 导入模块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47632435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES6 import module with Gulp
提问by Neil
I am trying to import my ES6 module into a file and running Gulp to concat and minify the file. I'm running into a ReferenceError: require is not defined at all.js(transpiled) line no 3. I have transpiled the code using gulp-babel.
我正在尝试将我的 ES6 模块导入一个文件并运行 Gulp 来连接和缩小文件。我遇到了一个ReferenceError: require is not defined at all.js(transpiled) line no 3。我已经使用 gulp-babel 转译了代码。
My js files are:
我的js文件是:
cart.js:
购物车.js:
class Cart{
constructor(){
this.cart = [];
this.items = items = [{
id: 1,
name: 'Dove Soap',
price: 39.99
},{
id: 2,
name: 'Axe Deo',
price: 99.99
}];
}
getItems(){
return this.items;
}
}
export {Cart};
app.js:
应用程序.js:
import {Cart} from 'cart.js';
let cart = new Cart();
console.log(cart.getItems());
gulpfile.js:
gulpfile.js:
"use strict";
let gulp = require('gulp');
let jshint = require('gulp-jshint');
let concat = require('gulp-concat');
let uglify = require('gulp-uglify');
let rename = require('gulp-rename');
let babel = require('gulp-babel');
// Lint Task
gulp.task('lint', function() {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
// Concatenate & Minify JS
gulp.task('scripts', function() {
return gulp.src('js/*.js')
.pipe(babel({
presets: ['env']
}))
.pipe(concat('all.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('all.min.js'))
.pipe(uglify().on('error', function(e){
console.dir(e);
}))
.pipe(gulp.dest('dist/js'));
});
// Default Task
gulp.task('default', ['lint','scripts']);
app.js(transpiled):
app.js(转译):
'use strict';
var _cart = require('cart.js'); //Uncaught ReferenceError: require is not defined
var cart = new _cart.Cart();
console.log(cart.getItems());
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Cart = function () {
function Cart() {
_classCallCheck(this, Cart);
this.cart = [];
this.items = items = [{
id: 1,
name: 'Dove Soap',
price: 39.99
}, {
id: 2,
name: 'Axe Deo',
price: 99.99
}];
}
_createClass(Cart, [{
key: 'getItems',
value: function getItems() {
return this.items;
}
}]);
return Cart;
}();
exports.Cart = Cart;
回答by JasonK
You would need a bundler like Webpackor Browserifyin order to use ES6 imports. Babel is only capable of compiling ES6 code to ES5 (native JS).
你需要一个像Webpack或Browserify这样的打包器来使用 ES6 导入。Babel 只能将 ES6 代码编译为 ES5(原生 JS)。
Both Webpack and Browserify have made recipes for gulp:
Webpack 和 Browserify 都为 gulp 制定了食谱:
- https://webpack.js.org/guides/integrations/#gulp
- https://github.com/gulpjs/gulp/tree/master/docs/recipes
- https://webpack.js.org/guides/integrations/#gulp
- https://github.com/gulpjs/gulp/tree/master/docs/recipes
Hope this helps.
希望这可以帮助。
回答by Daniel Tonon
Rollupis a good bundler for handling ES6 modules. It has native ES6 module support built in so it doesn't need to use Babel unlike Browserify.
Rollup是处理 ES6 模块的一个很好的打包器。它具有内置的原生 ES6 模块支持,因此与 Browserify 不同,它不需要使用 Babel。
Here is a Gulp 4 config that uses Rollup:
这是一个使用 Rollup 的 Gulp 4 配置:
// Gulp 4 file
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var rollup = require('@rollup/stream');
// *Optional* Depends on what JS features you want vs what browsers you need to support
// *Not needed* for basic ES6 module import syntax support
var babel = require('@rollup/plugin-babel');
// Add support for require() syntax
var commonjs = require('@rollup/plugin-commonjs');
// Add support for importing from node_modules folder like import x from 'module-name'
var nodeResolve = require('@rollup/plugin-node-resolve');
// Cache needs to be initialised outside of the Gulp task
var cache;
gulp.task('js', function() {
return rollup({
// Point to the entry file
input: './app.js',
// Apply plugins
plugins: [babel(), commonjs(), nodeResolve()],
// Enable source maps support
sourcemap: true,
// Use cache for better performance
cache: cache,
// Output bundle is intended for use in browsers
format: 'iife',
})
.on('bundle', function(bundle) {
// Update cache data after every bundle is created
cache = bundle;
})
// Name of the output file.
.pipe(source('bundle.js'))
.pipe(buffer())
// The use of sourcemaps here might not be necessary,
// Gulp 4 has some native sourcemap support built in
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('.'));
// Where to send the output file
.pipe(gulp.dest('./build/js'));
});
gulp.task('js:watch', function(done){
gulp.watch(['./source/**/*.js'], gulp.series('js'));
done();
})
gulp.task('default', gulp.series('js', 'js:watch'));

