E
E
Evgeny Zhurov2021-02-18 19:24:25
JavaScript
Evgeny Zhurov, 2021-02-18 19:24:25

How to configure webpack for this task?

By default, Webpack (we are talking about v. 5.22.0) puts the build in an anonymous function. I need to make a build in the form of a plugin that could be connected in an html file and initialized in this way:

<script src="widget.js"></script> // Подключение плагина
<script>
  new Widget().init() // Инициализация
</script>


I don't quite understand how to do it. The documentation says that you need to specify the value of library in the output. Made it like this

module.exports = {
  ...
  entry: './app.js',
  output: {
    library: 'Widget',
    filename: 'widget.js',
    path: PATH.resolve(__dirname, 'dist')
  }
}


However, this is not quite enough, because in the console the error "WIdget is not a constructor". Which is not surprising, because. Widget becomes a module with a default method that can be called. That is, this construction will work:

new Widget.default().init()

However, it will work only in the build version, but not in dev. And in any case, I want to remove this unnecessary default so that it can be called like this:

new Widget().init()

The Widget class itself is exported in the app.js file:

export default class Widget {
  constructor() {...}
  init() {...}
}


As a matter of fact, it is only required to call this very init method of the Widget class, without any intermediate default. How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2021-02-18
@delphinpro

see ready plugin config here https://github.com/delphinpro/cool-menu/blob/maste...

N
noys, 2017-10-12
@noys

RewriteEngine on
RewriteRule ^ru/pages$ /pages [R=301,L]
RewriteRule ^ru/articles$ /articles [R=301,L]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question