简体   繁体   中英

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:

  var a = 1;
  "use strict";

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

Please note that I am using jQuery as library. The browser returns the following error when I put the above code inside the document.ready function:

  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:

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

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

But nodeJS is for writing server code part. In case you want to run your code in browser you should look for webpack. With webpack for example you are able to write modules in ES6 syntax:

// 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.

For webpack you will need to create entry point for your app and define small config. Rest will be handled by this library, also webpack require NodeJs installed on your computer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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