简体   繁体   中英

react helper import fails in production but works in development

I've got a file called "globalHelper.js" like this:

exports.myMethod = (data) => {
  // method here
}

exports.myOtherMethod = () => { ... }

and so on...

I import my Helper in other files like this:

import helper from "../Helper/globalHelper";

Now there is the problem: In the past, everything worked with that when running my build-script:

"build": "GENERATE_SOURCEMAP=false react-scripts build"

but for some reason, when I run "npm run build", I get the error:

Attempted import error: '../Helper/globalHelper' does not contain a default export (imported as 'helper')

However, when I simply start my development server (npm start), everything works just fine.

I already tried to import like import { helper } from "../Helper/globalHelper"; , but that did not work either. Does someone know how to solve that?

Since you've not export default you should import the function with {} like:

  import {helper} from "../Helper/globalHelper";

try exporting like this with ES6 syntax

export const myOtherMethod = () => { ... }

then

import { myOtherMethod } from '...your file'

The method you are using exports.functionName is CJS. you need to use require to get the methods.

The CommonJS (CJS) format is used in Node.js and uses require and module.exports to define dependencies and modules. The npm ecosystem is built upon this format.

If you want to use module method you can do this.

export { myOtherMethod1, myOtherMethod2 }

then you import like this.

import * as Module from '....file name'

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