如何在ECMAScript 6中使用模块?

时间:2015-11-26 18:42:51

标签: javascript babeljs commonjs

我尝试使用此代码作为示例,并使用Babel

编译此代码
let notExported = 'abc';
export function square(x) {
    return x * x;
}
export const MY_CONSTANT = 123;
编译后

Object.defineProperty(exports, '__esModule', { value: true });
exports.square = square;
var notExported = 'abc';
function square(x) {
    return x * x;
}
var MY_CONSTANT = exports.MY_CONSTANT = 123;

但是浏览器显示错误:“未捕获的ReferenceError:导出未定义”。我做错了什么?也许我需要使用一些库(如果是的话,怎么做)?

1 个答案:

答案 0 :(得分:2)

Babel会将ES6模块语法转换为其他模块格式。默认的是CommonJS。 Node默认支持CommonJS。如果您希望在浏览器中使用CommonJS模块,则需要在Webpack或Browserify等模块捆绑器旁边使用Babel。您可以使用以下内容:

# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

# Project target.
target=android-23
android.library.reference.1=../appcompat_v7

并与

捆绑在一起
npm install browserify babelify

然后在浏览器中加载./node_modules/.bin/browserify -t babelify yourFile.js -o bundledFile.js