简体   繁体   English

学习 Webpack:如何在 webpack 中包含库并在浏览器中使用

[英]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 ).我想使用tailwindcss和一个日期选择器(js-datepicker: https://github.com/qodesmith/datepicker )。

src/index.js: src/index.js:

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

webpack.config.js 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现在我想在我的浏览器中使用日期选择器,所以我将生成的“bundle.js”包含在我的 HTML 中

but

const picker = datepicker('#someid')

generated an error: "ReferenceError: datepicker is not defined"生成错误:“ReferenceError:未定义日期选择器”

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...如果我查看生成的 bundle.js,我可以看到所有顺风 styles 和 datepicker-code...

You can add datepicker to window , and then you can use it in browser.您可以将datepicker添加到window ,然后您可以在浏览器中使用它。

In your index.js file在您的index.js文件中

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM