简体   繁体   English

如何在ECMAScript 6中使用模块?

[英]How to use modules in ECMAScript 6?

I try use this code for example, and compile this code with Babel 例如,我尝试使用此代码,并使用Babel编译此代码

let notExported = 'abc';
export function square(x) {
    return x * x;
}
export const MY_CONSTANT = 123;

after compile: 编译后:

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;

but browser show error: " Uncaught ReferenceError: exports is not defined ". 但是浏览器显示错误:“ Uncaught ReferenceError:未定义导出 ”。 What i do wrong? 我做错了什么? Maybe i need use some libs (if yes, how do it)? 也许我需要使用一些库(如果是,怎么做)?

Babel will convert ES6 module syntax into other module formats. Babel会将ES6模块语法转换为其他模块格式。 The default one is CommonJS. 默认的是CommonJS。 Node supports CommonJS by default. 默认情况下,Node支持CommonJS。 If you wish to use CommonJS modules in a browser, you'll need to use Babel along side a module bundler like Webpack or Browserify. 如果您想在浏览器中使用CommonJS模块,则需要在Webpack或Browserify等模块捆绑器旁边使用Babel。 You'd use something along the lines of: 您将使用以下方式:

npm install browserify babelify

and bundle with 并与

./node_modules/.bin/browserify -t babelify yourFile.js -o bundledFile.js

then load bundledFile.js in your browser. 然后在您的浏览器中加载bundledFile.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM