Vito Lipari
Vito Lipari

Reputation: 869

React - How to use npm-linked module

How can I use a module imported via

npm link

into webpack for a React application?

MyModule_Folder
---------------------------------
    |--package.json
    |--src
        |--myModule
            |--MyComponent.jsx
            |--MyStyle.css
            ...
    |--public
        |--index.html

App
---------------------------------
    |--package.json
    |--src
        ...

MyModule/package.json is like this

{
    "name": "@mymodule/external",
    "version": "1.0.0",
    "main": "src/index.jsx",
    "babel": {
        ...
    },
    "devDependencies": {
        ...
    },
    "dependencies": {
        ...
    },
    "scripts": {
        ...
    }
}

I typed

cd <path_to_MyModule_Folder>
npm link
cd <path_to_MyReactApp>
npm link @mymodule/external

If I import my module in this way

import { MyModuleClass } from "@mymodule/external";

I got an error

Upvotes: 0

Views: 4404

Answers (1)

Milos Mosovsky
Milos Mosovsky

Reputation: 2983

You have wrong importing exporting the MyModule

MyModule.js

import React from 'react'

export function helloWorld() {}

Class Esterno extends React.Component {
  render() { ..... }
}

export default Esterno

index.js

export * from './MyModule.js'

now imagine it's usage

import Esterno from 'mymodule'

console.log(Esterno)

you are now importing all contents of module (*) so the otuput will be

object = {
 helloWorld: function() {}
 default: class Esterno {}
}

now let's change the export in index.js

export default from './MyModule.js`

now the console log will output

object = class Esterno {}

so you are missing difference between export/import * and default default is default module and * is object of all exports from within module.

Upvotes: 1

Related Questions