Creating an NPM Module: Importing your own package as a dependency

Currently, I am in the process of developing a new NPM package. The repository includes an examples directory containing some JavaScript code that is compiled and served locally (or potentially through github.io).

The configuration is reminiscent of the setup in react-menu. If you examine any of the JavaScript files within the examples directory, you'll notice that they import the package as if it was just installed using npm install react-menu:

import Menu, { SubMenu, Item as MenuItem } from 'rc-menu';

Surprisingly, the package is not listed under dependencies in the package.json file.

I am aware that I can import my own module by specifying something like

import myThing from '../../../index.js'
, but I prefer not having to deal with multiple relative directories. I attempted to import my module using import myThing from 'my-thing', but the package was not found and the import failed.

How exactly is react-menu accomplishing this?

Answer №1

After digging a bit deeper into the webpack documentation, I found the solution.

In summary, the answer lies in adjusting the resolve configuration setup.

This is how my directory structure looks:

.
├── LICENSE.md
├── README.md
├── examples
│   ├── bundle.js
│   ├── index.html
│   ├── server.js
│   └── src
│       ├── components
│       │   ├── App.js
│       │   └── examples
│       │       └── ExampleOne.js
│       └── index.js
├── index.js
├── package-lock.json
├── package.json
├── src
│   └── index.js
├── test
├── webpack.config.js
└── webpack.examples.config.js

The simple addition of the resolve configuration in my webpack.config.examples.js file solved the issue. Here's the complete file for reference:

const webpack = require('webpack')
const path = require('path')

module.exports = {
    entry: [
        'react-hot-loader/patch',
        'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
        './examples/src/index.js',
    ],

    output: {
        path: path.resolve(__dirname, 'examples'),
        publicPath: '/',
        filename: 'bundle.js',
        sourceMapFilename: 'bundle.js.map',
    },

    resolve: {
        alias: {
            'my-package': path.resolve(__dirname, 'src'),
        },
    },

    devtool: 'eval-source-map',

    plugins: [
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
        new webpack.NoEmitOnErrorsPlugin(),
    ],

    module: {
        rules: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                use: ['babel-loader'],
            },
        ],
    },
}

Now, whenever I'm working within the examples app, I can simply import modules like this:

import myThing from 'my-package'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for incorporating WinBox JS into Angular applications

I've been experimenting with the WinBoxJS JavaScript library, and I'm familiar with using it in plain JS. However, I'm now attempting to integrate it into my Angular project. Can anyone guide me on how to achieve this? https://www.npmjs.com/ ...

Utilizing the scrollTop method to display the number of pixels scrolled on

My goal is to show the number of pixels a user has scrolled on my website using the scrollTop method in jQuery. I want this number of pixels to be displayed within a 'pixels' class. Therefore, I plan to have <p><span class="pixels"> ...

Is javascript or ajax the best choice for updating a database in asp.net mvc?

I need help with updating a row in my database based on a change event from a dropdown list. I am not sure whether to use javascript or ajax for this purpose as I want to avoid page refresh. Any recommendations on which method is best and where I can find ...

Turn off base64 encoding for background URLs in the Minify package

When I use the minify tool to compress my js and css files, I noticed that the files containing background:url(...) statements actually increased in size. This happened because the urls were encoded to base64. I tried to disable this base64 encoding featu ...

Having trouble setting up gulp installation

Every time I try to set up my developer environment from scratch, I encounter problems with gulp. npm install gulp-cli -g npm : npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="01726e747362642c6c60712c74..."&g ...

Sign in to npm using various scopes

npm provides the ability to specify a scope for a registry during login using the following command: npm login --scope=@my-company-name --registry=http://your-server-address:8080 Can multiple scopes be assigned during the same login session? This is a q ...

Exploring the nuances of npm configuration: global versus local settings

Below are some resources regarding the topic: https://docs.npmjs.com/cli/config It seems that the following commands are the same: npm config set foo bar npm set -g foo bar Therefore, I assumed that if I use npm set without the -g option, it would upda ...

What is the process for triggering a sorted output from my MongoDB database by simply clicking a button?

I'm struggling with sorting my collection by rating in my code. I have this snippet where I'm sending my collection to index.ejs: router.get('/', (req, res) =>{ FILM .find().limit(6) .then(films => res.render(& ...

How can I use an HTML button to activate a function that inserts text into a read-only text-box?

Trying to write a simple piece of HTML code that finds the number greater than or equal to the first initial amount that wholly divides the second given amount. The code attempts to divide the numbers, and if it fails, increments the first number by 1 and ...

Transmit information from an HTML input field (not a form) to a Python CGI script through AJAX

I am currently facing a challenge where I need to send data programmatically without using form fields directly to a python CGI script. The issue lies in not knowing how to extract this data in Python. Normally, with a form, I could use "form = cgi.FieldSt ...

pm2 is launching multiple instances of identical next.js applications

I am in the process of deploying my Next.js app on my local PC. Below are the contents of my configuration and package.json files: // package.json { "name": "smarf", "private": true, "scripts": { "dev ...

Incorporating a JavaScript workflow into Django

Currently, I am following a tutorial on integrating a modern JavaScript pipeline into my Django application. The objective is to have the JavaScript code write "Hello webpack" onto the page, but unfortunately, it is not displaying as expected. Since I alr ...

`Switching the selection in ng-selected`

I am having trouble toggling ng-selected options in Angular. I have tried the following approach: <select ng-model="datacut.ages" multiple> <option value="" disabled="disabled">Please Select</option> <option value="0-15" ng-clic ...

Hold off on running the code until the image from the AJAX request is fully loaded and

Currently, I am facing a challenge with my code that aims to determine the width and height of a div only after it has been loaded with an image from an AJAX request. The dimensions of the div remain 0x0 until the image is successfully placed inside it, c ...

Validating form field values in JavaScript prior to submission

My website features a search box that allows users to search through a database of books. When utilizing the search feature, users are presented with the following options: Search Query (a text input field) Where to search (a select field with the option ...

Retrieve the value of a dropdown menu that contains multiple selections associated with a single model

My current code generates a calendar entry listing for the courtroom, with each case having a "status" dropdown that is set by the judge post-hearing. I now need to save this data in the database. I have successfully added ng-change which triggers the desi ...

Encountering an issue with authentication credentials while using NPM dependencies on Google Cloud AppEngine

After creating a Node.js project called "AA" in Google Cloud (GC) Repository, I proceeded to create another project labeled "BB" and included "AA" as a dependency: "dependencies": { "@slack/client": "^4.9.0", "axios": "^0.18.0", "big-integer": "^1.6 ...

Incorporate a JSON file into the Webpack output separately from the bundle.js file

Is there a way for my webpack application to read a JSON file at runtime without including it in the bundle.js after packaging? I want the JSON file to be available in the package folder but not bundled with the rest of the code. How can I achieve this? ...

TinyMCE generates HTML code with embedded tags

Hey there, I'm currently facing an issue with TinyMCE that I just can't seem to solve. I've browsed through some related posts but haven't found a solution that works for me... For example: When I input something in my back office, ...

Searching to loop through JSON within a Sequelize / Postgres database query in order to identify a corresponding value

Hello everyone, I'm new here so please bear with me. I'm currently working on a project using Sequelize with PostgresDB in Node and I need to search for a contact by email using findOrCreate function. The email entry is stored in JSON format (se ...