Ulf
Ulf

Reputation: 1

Learning Webpack: how to include library in webpack and use in browser

I thought this question must have been asked many times but I could not find a suitable answer. Maybe its because I do not know all the buzzwords correctly...

So, I tried to use bundling for a new project (to keep up to date) and had a small test. I want to use tailwindcss, and a datepicker (js-datepicker: https://github.com/qodesmith/datepicker).

src/index.js:

import './styles.css'
import datepicker from 'js-datepicker'

webpack.config.js

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

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname,'dist'),
        filename: 'bundle.js'
    },

    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options: {importLoaders: 1}
                    },
                    'postcss-loader'
                ]
            }
        ]
    },
    plugins: [
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
    ]
}

and now I want to use the date picker in my browser, so I included the generated 'bundle.js' into my HTML

but

const picker = datepicker('#someid')

generated an error: "ReferenceError: datepicker is not defined"

What is the magic trick I am missing? If I look at the generated bundle.js, I can see all the tailwind styles and the datepicker-code...

Upvotes: 0

Views: 312

Answers (1)

user11081925
user11081925

Reputation:

You can add datepicker to window, and then you can use it in browser.

In your index.js file

import './styles.css'
import datepicker from 'js-datepicker'

// Add datepicker to window object
window.datepicker = datepicker;

Upvotes: 1

Related Questions