eden_lane
eden_lane

Reputation: 108

How can use my module as an external library in my project with webpack?

I'm trying to use my module as an external library in my project. Here is the code of my library:

// src/index.js
export default {
    test: 'Hello there'
}

here is package.json of my library:

  "main": "dist/index.js",
  "module": "src/index.js",

and that's how I import it in my project:

import { test } from 'my-library'
import external from 'my-library'

console.log(test) // logs undefined
console.log(external.test) // logs 'Hello there'

Why destructuring doesn't work? Here is webpack config of my project:

module: {
        rules: [
            {
                test: /\.js$/,
                // exclude: /node_modules/,
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/react'],
                    plugins: ['transform-class-properties']
                }
            },
        ]
}

Upvotes: 0

Views: 448

Answers (1)

Trash Can
Trash Can

Reputation: 6814

This syntax import { symbol } from 'library' is used to import non-default exports, while this syntax import someNamespace from 'my-library' is used to import the default export, and because your module only has default export, you have to use the second syntax to correctly grab it, that's why your first import returns undefined

If you change the content of your module to the following

export const test = 'Hello there'

Then the first import will make the console.log() print Hello there, while the second import will throw an error because your module lacks the default export

Upvotes: 1

Related Questions