問題描述
考慮以下示例代碼(也許我做錯了?)
Consider the following example code (and maybe I am doing it wrong?)
var FlareCurrency = {
};
export {FlareCurrency};
我有以下任務:
gulp.task("compile:add-new-currency-minified", function(){
return gulp.src('src/add-new-currency/**/*.js')
.pipe(babel())
.pipe(concat('Flare-AddNewCurrency.js'))
.pipe(uglify({"preserveComments": "all"}))
.pipe(gulp.dest('dist/minified/'));
});
當我運行它時,我得到以下信息:
When I run this I get the following:
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var FlareCurrency={};exports.FlareCurrency=FlareCurrency;
為了好玩,我想在控制臺中運行它,是的,我知道它什么也沒做,但我沒想到會看到這個:
For the fun of it, I wanted to run it in the console, yes I know it does nothing but I didn't expect to see this:
Uncaught ReferenceError: exports is not defined(…)
非縮小版:
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var FlareCurrency = {};
exports.FlareCurrency = FlareCurrency;
拋出同樣的錯誤.想法?
推薦答案
這實際上不是 babel 問題,您只是嘗試在瀏覽器中運行 CommonJS 代碼(從 ES6 export
轉譯)準備.CommonJS 不在瀏覽器上運行,需要使用工具為瀏覽器打包,例如 Webpack 或 瀏覽器.
That is not actually a babel issue, you are just trying to run CommonJS code (transpiled from ES6 export
) in the browser without preparation. CommonJS doesn't run on the browser, you need to use a tool to package it for the browser, such as Webpack or Browserify.
本周巧合的是,我在 Github 上創建了一個小項目,展示了 Gulp + ES6 代碼(使用 export
)+ Babel + Webpack 的設置:gulp-es6-webpack-example.
Just by coincidence this week I created a small project on Github that shows a setup of Gulp + ES6 code (using export
) + Babel + Webpack: gulp-es6-webpack-example.
在我的示例中,您可以在瀏覽器上同步(預加載)或異步(延遲加載)加載 JS 代碼.
In my example you can load JS code on the browser either synchronously (pre-loaded) or asynchronously (lazy-loaded).
這篇關于gulp babel,未定義導出的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!