Importing git npm modules results in undefined

Viewed 113

I have made a npm module in a private git repo and I'm trying to access it in another application. I'm using reactjs, webpack and npm

So I have the module:

    dist
    src
    |   form-mapper
        |   formMapper.js
    |   myfile.js
    |   index.js
    package.json
    webpack.config.js

Webpack.config.js is like this:

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js'
    }
}

Package.json is like this:

{
  "name": "my-awesome-module",
  "version": "1.0.0",
  "license": "ISC",
  "main": "./dist/bundle.js",
  "scripts": {
    "prepare": "npm run build",
    "build": "webpack --mode production",
    "start": "webpack-dev-server --open --mode development"
  },
  "devDependencies": {
    "webpack": "^4.43.0",
    "webpack-cli": "^4.3.0",
    "webpack-dev-server": "^3.11.0"
  }
}

formMapper.js as 2 functions that I'm trying to export:

    export function mapForm() {
        // some code
    }
    export function mapUiFormToBackEnd() {
        // some code
    }

And index.js:

import * as FormMapper from './form-mapper/formMapper'

export { mapForm, mapUiFormToBackEnd } from './form-mapper/formMapper'
export default FormMapper

I've tried a lot of things in index.js so I let everything here just to show you guys what I've already tried.

In my app that needs to use this module I import the module using npm (git+ssh://...) which is working since I can see my module inside node_modules. When I try to import using:

import FormMapper from 'my-awesome-module'

componentDidMount() {
   FormMapper.mapForm()
}

I have this error:

my-awesome-module__WEBPACK_IMPORTED_MODULE_2___default.a.mapForm is not a function

That's my first time trying to create my own npm module and I clearly don't understand everything. I tried several guide but it seems I'm not abla to make it right.

Thanks for the help.

Edit: When I log my import in my application

import FormMapper from 'my-awesome-module'

componentDidMount() {
   console.log(FormMapper)
   FormMapper.mapForm()
}

I see an empty object {} getting logged

1 Answers

update your formMapper.js in a more proper way

const mapForm = () => {
    // Code here
}
const mapUiFormToBackEnd = () => {
    // Code here
}
module.exports = {mapForm, mapUiFormToBackEnd }

on your index.js

// If you just want the mapForm and mapUiFormToBackEnd
const {mapForm, mapUiFormToBackEnd} = require('./form-mapper/formMapper');

// Or if you just want to get all it's fucntion just import it like this
const FormMapper = require('./form-mapper/formMapper') // No need for *

// export the whole FormMapper
module.exports = FormMapper;

// If you want to export a specific functions inside FormMapper
module.exports = {mapForm, mapUiFormToBackEnd }
Related