Laravel Mix for Webpack - 除非它在 DOMContentLoaded 事件中,否则不运行 Javascript 代码

问题描述 投票:0回答:0

我正在为我的 WordPress 主题使用 Laravel Mix 和 Webpack。现在我注意到节点模块和包,例如 Swiper JS 将无法运行,除非我将函数包装在

document.addEventListener('DOMContentLoaded')
中是否有绕过它的技巧?我被迫使用这个。

这是我的 webpackmix.js:

const mix = require('laravel-mix');
const path = require('path');

mix.setResourceRoot('../');
mix.setPublicPath(path.resolve('./'));

mix.alias({
   '@': path.join(__dirname, './src')
});

mix.webpackConfig({
   watchOptions: {
      ignored: [
         path.posix.resolve(__dirname, './node_modules'),
         path.posix.resolve(__dirname, './build/css'),
         path.posix.resolve(__dirname, './build/js')
      ]
   },

   module: {
      rules: [
         {
            test: /\.ts?$/,
            loader: 'ts-loader',
            exclude: /node_modules/
         }
      ]
   },
   resolve: {
      extensions: ['*', '.js', '.jsx', '.ts', '.tsx']
   }
});

mix.js('src/scripts/app.ts', 'build/js');

mix.postCss('src/styles/app.css', 'build/css');

mix.postCss('src/styles/editor-style.css', 'build/css');

mix.browserSync({
   files: ['**/*.php', './build/js/*'],
   proxy: 'http://website.local',
   host: 'website.local',
   open: 'external',
   logLevel: 'silent',
   notify: false,
   port: 8000
});

mix.inProduction() ? mix.version() : (Mix.manifest.refresh = (_) => void 0);

tsconfig.json:

{
   "compilerOptions": {
      "target": "es5",
      "module": "commonjs",
      "noImplicitAny": false,
      "sourceMap": false
   },
   "include": ["./src/scripts/**/*"],
   "exclude": ["node_modules"]
}

还有 slider.ts 的代码:

从'swiper'导入{Pagination,Swiper};

import 'swiper/css';
import 'swiper/css/pagination';

const Slider = () => {
   new Swiper('.mySwiper', {
      modules: [Pagination],
      loop: true,
      slidesPerView: 1.5,
      spaceBetween: 40,
      centeredSlides: true,
      pagination: {
         el: '.swiper-pagination',
         dynamicBullets: true
      }
   });
};

document.addEventListener('DOMContentLoaded', Slider);
webpack laravel-mix
© www.soinside.com 2019 - 2024. All rights reserved.