简体   繁体   English

无法使用Javascript中的Object.defineProperty导出变量

[英]Variables cannot be exported with Object.defineProperty in Javascript

I am trying to export variables from one JS document to another using the following syntax: 我正在尝试使用以下语法将变量从一个JS文档导出到另一个:

  var a = 1;
  "use strict";

 Object.defineProperty(exports, "__esModule", {
 value: true
});
exports.a = a;

Please note that I am using jQuery as library. 请注意,我正在使用jQuery作为库。 The browser returns the following error when I put the above code inside the document.ready function: 当我将以上代码放入document.ready函数中时,浏览器返回以下错误:

  jquery-3.3.1.min.js:2 Uncaught ReferenceError: exports is not defined
    at HTMLDocument.<anonymous> (index.js:1560)
    at l (jquery-3.3.1.min.js:2)
    at c (jquery-3.3.1.min.js:2)

Do I need to install preprocessors or something is wrong with my syntax? 我是否需要安装预处理器或语法有问题?

So the answer is you need a module bundler to handle modules imports exports in brower. 因此,答案是您需要一个模块捆绑器来处理模块导入中的导出。 In nodeJS you can use commonJS module sytax: 在nodeJS中,您可以使用commonJS模块语法:

// test.js
module.exports = function () {};

// main.js
var test = require('./test');

But nodeJS is for writing server code part. 但是nodeJS是用于编写服务器代码的一部分。 In case you want to run your code in browser you should look for webpack. 如果要在浏览器中运行代码,则应查找webpack。 With webpack for example you are able to write modules in ES6 syntax: 以webpack为例,您可以使用ES6语法编写模块:

// test.js
export default function () {}

// main.js
import test from './test';

Please learn about webpack: https://webpack.js.org/concepts/ Its not so difficult to setup it any project. 请了解有关webpack的信息: https ://webpack.js.org/concepts/对其进行任何项目设置都不是那么困难。

For webpack you will need to create entry point for your app and define small config. 对于webpack,您将需要为您的应用创建入口点并定义小型配置。 Rest will be handled by this library, also webpack require NodeJs installed on your computer. 其余的将由该库处理,而且webpack要求在计算机上安装NodeJ。

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

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