R
R
romaro2021-07-06 22:36:13
JavaScript
romaro, 2021-07-06 22:36:13

How to connect the script correctly when building with Webpack?

Wrote a training script that should process the form on the page. During debugging, the code was after the body tag and everything worked. Then I transferred the script to a separate file and added it to the imports. Pre-connected Babel, because. I had an error when trying to compile the project (the handler cursed for the presence of a class).

After assembly, the script gets into the bundle, which is included before the body tag:

<script defer src="../bundle.js"></script><link href="../style.css" rel="stylesheet"></head>


At the same time, I left the call to this script at the bottom of the page:
... Код страницы ...
</footer>
    <script>
        // regForm —это название формы, для которой инициализирую класс, который содержит обработчики. На странице, теоретически, может быть несколько форм.
        const regForm = new FormHandler('reg-form');
        regForm.init();
    </script>
</body>


Now, after loading the page, I get the error "FormHandler is not defined".

If I understand correctly, it's not just that the script needs to be included after the body tag? Is the problem also related to the fact that the form handler is initialized around Babel?

How, after all, to connect such scripts that can create several instances of a class on a page?

Answer the question

In order to leave comments, you need to log in

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

It's not about babel, and it's not about webpack.
https://learn.javascript.ru/script-async-defer

E
Egor Danchenko, 2021-07-24
@YahorDanchanka

Better use the HtmlWebpackPlugin, which automates the scripting and styling for you. A good Webpack config is the bare minimum of what you need to do.

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    index: path.resolve(__dirname, 'src/scripts/example.js')
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'src/index.html'),
      // Скрипты, которые нужно подключить к странице
      chunks: ['index'],
      // Логика загрузки
      scriptLoading: 'blocking | defer'
    })
  ],
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question