简体   繁体   中英

What is the difference between export function and module.exports?

I have a Javascript file utils.js which contains some utility functions. Here is an example:

export function RemoveHTML(Str) {
    return Str.replace(/<[^>]*(?:>|$)/gi,'');
}

I can use these functions by importing the utils.js file like such:

import {RemoveHTML} from '../js/utils.js';

I also have a model.js file for some data queries like this (pseudo-code for brevity):

async function getStuff() {
    await DBConnection.connect();
    return results
}

module.exports = {
  getStuff
}

For 'consistency' I thought I'd change model.js to just this:

export async function getStuff() {
    await DBConnection.connect();
    return results
}

If I do that then I get an app crash error stating:

SyntaxError: Unexpected token 'export'

What is the difference between exporting a function using export function() and module.exports ?

UPDATE:

I am using Babel in Webpack like below so why would I get an error?:

{
      test: /\.js$/,
        include: [ srcPath ],
      exclude: ['/node_modules/'],
      use: {
        loader: 'babel-loader',
        options: {
          presets: ["@babel/preset-env"]  //Preset used for env setup
        }
      }
    },

export function() is an ES6 syntax used for exporting while module.exports is or exports is a special object which is included in every JS file in the Node.js application by default.
You can also use the ES6 syntax for exporting/importing a module in Node.js but for using that you will have to transpile the new ES6 code to Node.js supported ES5 format, You can easily do that using babel (which is a tool for transpiling JavaScript).

@JonasWilms is definitely correct about the point he made. I see you are using commonjs on the server code and es6 on the client-side.

There is no difference between module.export or export. In your project, your server code is using commonjs modules, so you should use module.exports. In your client code, keep on using export (es6) syntax of JavaScript.

But if you want to write your javascript globally with es6, you will have to install some dependencies and configure your babel.

Check out this link https://www.codementor.io/@iykyvic/writing-your-nodejs-apps-using-es6-6dh0edw2o

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