@Esm322

Как правильно настроить webpack?

Подскажите, пожалуйста, по настроке webpack, шёл по документации. Подключал плагины и лаудеры для проекта, но после установки babel всё полетело, и страница перестала отображаться и появилась ошибка "Uncaught TypeError: Cannot read properties of null (reading 'nodeType')". Решил проверить пошагового в чём проблема, ведь до babel всё работало. Создал другой проект, но не загружал пакет babel, и появились такая же ошибка. В чем может быть проблема? Заранее, спасибо.
webpack config:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");

module.exports = (env) => ({
  entry: './src/index.js',
  output: {
    filename: 'main.[hash].js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env']
            ]
          }
        }
      },
      {
        test: /\.css$/i,
        use: [
          env.prod ? MiniCssExtractPlugin.loader : "style-loader",
          "css-loader",
        ],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
      {
        test: /\.(svg)$/i,
        type: "asset",
      },
    ],
  },
  optimization: {
    minimizer: [
      "...",
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.svgoMinify,
          options: {
            encodeOptions: {
              multipass: true,
              plugins: [
                "preset-default",
              ],
            },
          },
        },
      }),
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Форма оплаты',
    }),
    new MiniCssExtractPlugin({
      filename: 'main.[hash].css'
    })
  ],
  devServer: {
    historyApiFallback: true,
    hot: true,
  },
});


package.json:
"private": true,
  "scripts": {
    "lint": "eslint ./",
    "lint:report": "eslint ./",
    "build": "webpack --mode=production --env prod",
    "dev": "webpack serve --mode=development"
  },
  "devDependencies": {
    "@babel/core": "^7.23.3",
    "@babel/preset-env": "^7.23.3",
    "babel-loader": "^9.1.3",
    "css-loader": "^6.8.1",
    "eslint": "^7.15.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-formatter-gitlab": "^2.1.0",
    "eslint-plugin-import": "^2.22.1",
    "html-webpack-plugin": "^5.5.3",
    "image-minimizer-webpack-plugin": "^3.8.3",
    "mini-css-extract-plugin": "^2.7.6",
    "style-loader": "^3.3.3",
    "svgo": "^3.0.4",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  },
  "dependencies": {
    "@maskito/core": "^1.8.2",
    "@maskito/kit": "^1.8.2",
    "babel-polyfill": "^6.26.0",
    "card-validator": "^9.0.0",
    "redom": "^3.29.1",
    "validator": "^13.11.0"
  }
}


index.html:
<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app"></div>

  <script src="/dist/main.js"></script>
</body>
</html>


index.js:
import 'babel-polyfill';
import {Maskito, MaskitoOptions} from '@maskito/core';
import maskitoOptions from './mask/mask.js';
import { el, mount, setChildren } from "redom";
import validator from 'validator';
import visa from './mixins/payment-system/visaSVG.js';
import mir from './mixins/payment-system/mirSVG.js';
import masterCard from './mixins/payment-system/mastercardSVG.js';
import './styles/style.css';

let valid = require("card-validator");

const app = document.getElementById('app');

function formPay() {
  const form = el('form.form');
  const inputNumberCard = el('input.input.number', {placeholder: '0000 0000 0000 0000'});
  const inputDate = el('input.input.date', {placeholder: 'мм/гг'});
  const inputCVC = el('input.input.cvc', {placeholder: '000'});
  const inputEmail = el('input.input.email', {placeholder: 'Email'});
  const btn = el('button.btn', {textContent: 'Отправить', disabled: true});
  const liner = el('span.liner');
  const wrapperFirstLvl = el('div.wrapper');
  const wrapperSecondLvl = el('div.wrapper');
  const wrapperImg = el('div');

  const firstInput = new Maskito(inputNumberCard, {
    mask: [
      ...new Array(4).fill(/\d/),
      ' ',
      ...new Array(4).fill(/\d/),
      ' ',
      ...new Array(4).fill(/\d/),
      ' ',
      ...new Array(4).fill(/\d/),
      ' ',
      ...new Array(2).fill(/\d/),
    ],
  });

  const secondInput = new Maskito(inputDate, maskitoOptions);

  const thirdInput = new Maskito(inputCVC, {
    mask: /^\d{0,3}$/,
  })

  window.addEventListener('input', () => {
    const validatorCardNumber = valid.number(inputNumberCard.value);
    const validatorCardDate = valid.expirationDate(inputDate.value);

    wrapperImg.innerHTML = '';
    if (inputNumberCard.value.startsWith('4')) {
      setChildren(wrapperImg, visa)
    } else if (inputNumberCard.value.startsWith('2')) {
      setChildren(wrapperImg, mir)
    } else if (inputNumberCard.value.startsWith('5')) {
      setChildren(wrapperImg, masterCard)
    }

    if (validatorCardNumber.isValid && inputCVC.value.length === 3 && validatorCardDate.isValid && validator.isEmail(inputEmail.value)) {
      btn.disabled = false
    }

    if (!validatorCardNumber.isValid || inputCVC.value.length !== 3 || !validatorCardDate.isValid || !validator.isEmail(inputEmail.value)) {
      btn.disabled = true
    }
  })

  setChildren(wrapperFirstLvl, [inputNumberCard, wrapperImg])
  setChildren(wrapperSecondLvl, [inputDate, liner, inputCVC])

  setChildren(form, [wrapperFirstLvl, wrapperSecondLvl, inputEmail, btn])

  mount(app, form)
}

formPay()
  • Вопрос задан
  • 102 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы