📜  js import export es5 - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:29.327000             🧑  作者: Mango

JS import/export with ES5

In the world of JavaScript, ES5 is an older version of the language that is still widely used today. One of the features introduced in ES6 is the import and export statements, which allow for modules to be imported and exported between different files.

However, it is still possible to use import and export statements in ES5 by using a module bundler, such as Browserify or Webpack. These tools allow developers to write code using the ES6 syntax and then bundle it down to ES5 code that can be used in older browsers.

Importing modules

To import a module into an ES5 file, we can use the require statement provided by Node.js. For example, to import the foo module from a file called bar.js, we would write:

var foo = require('./bar');

This assumes that bar.js is located in the same directory as the file we are importing it into. The require statement returns the value of the module.exports object in the specified file.

Exporting modules

To export a module from an ES5 file, we can set the module.exports property to the value we want to export. For example, to export a function called baz from a file, we would write:

function baz() {
  console.log('hello world');
}

module.exports = baz;

This will allow other files to import the baz function using the require statement as described above.

Conclusion

While ES6 introduced a number of new features to JavaScript, it is still possible to use some of these features in older versions of the language by using a module bundler. By using the require statement to import modules and setting the module.exports property to export modules, we can write modular, maintainable code even in ES5.