2

I have been struggling for the past couple days to get this working properly.

I have two classes in two different js files:

file src/a.js:

export default class A {}

file src/b.js:

export default class B {}

and I have the following entrypoint file:

file src/index.js:

import A from './a.js'
import B from './b.js'

export { A, B }

// I don't know what else should go in here

I build it using this webpack config:

file webpack.config.js:

module.exports = {
  input: 'src/index.js',
  output: {
    path: 'dist/',
    filename: 'my-lib.js',
    libraryTarget: 'commonjs-module',
  }
}

And build it with the webpack command.

Another thing to note is the package.json:

file package.json:

{
  "name": "my-library",
  "module": "dist/my-lib.js",
  "main": "dist/my-lib.js"
}

The goal is to import my node module in another project atfer installing it:

$ npm install --save my-module

And use it like this:

import {A,B} from 'my-module' 

const a = new A()
const b = new B()

How do I create such an index.js file and how should my webpack.config.js file look to be able to do this?

arielnmz
  • 8,354
  • 9
  • 38
  • 66
  • If you look at the official webpack example, you will find that they export it as `umd`. See here: https://github.com/kalcifer/webpack-library-example/blob/master/webpack.config.babel.js. This is linked from the official documentation here: https://webpack.js.org/guides/author-libraries/ – Domi Jun 19 '20 at 17:52

1 Answers1

-2

By the look of it you have two projects. In project 1 you are creating a library.

For creating libraries see https://webpack.js.org/guides/author-libraries/

but basically you need to export those classes for use by the other project

import A from './a.js'
import B from './b.js'

module.exports = {
  A,
  B
}

Then in the second project you can import those modules

import {A,B} from 'my-module' 
SoluableNonagon
  • 11,541
  • 11
  • 53
  • 98
  • What about the webpack config? this doesn't work, I get export A was not found in 'my-module' – arielnmz Jun 18 '20 at 03:28
  • You haven't provided a config in your question. Try this question: https://stackoverflow.com/questions/41359740/how-to-bundle-a-library-with-webpack and see the repo referenced in the answer https://github.com/UsulPro/libpack – SoluableNonagon Jun 18 '20 at 03:45
  • Well that's exactly what I'm asking for: what is a valid webpack config to produce a module that I can use like this? – arielnmz Jun 18 '20 at 04:38
  • This link provides such an example https://webpack.js.org/guides/author-libraries/ – SoluableNonagon Jun 18 '20 at 16:21
  • It doesn't work, it's just like the example in the OP – arielnmz Jun 19 '20 at 17:20