简体   繁体   中英

How do I include external libraries using Webpack in a Wordpress theme

I've decided I want to use Webpack and Babel to develop my Wordpress theme because I want to support ES6 features and still have my website work on older browsers (IE11), as well as other benefits such as being able to import files so that I don't have to have all of my JS in one big script.js file (eg for themes that use WebGL).

It's my first time setting up and using Webpack, I'm pretty sure I have it all set up in the correct way because I followed a few tutorials to do it and it's all working great, but my main question is with using external libraries. I have a couple that I need to use (ie Chart.js, Flickity, Magnific Popup, etc...) installed via NPM. I have a main script.js file that contains my normal Javascript code and gets bundled into bundle.min.js which is the file that is enqueued with Wordpress.

What is the best way to use external libraries alongside my script.js file with webpack?

At the moment the best solution I came up with is to have my script.js file setup in the following way:

// Imports
import 'magnific-popup/dist/jquery.magnific-popup.min.js';
import 'flickity/dist/flickity.pkgd.min.js';
import 'chart.js/dist/Chart.bundle.min.js';



script.js code...

When I run npm run build it all works fine and babel and uglify js work their magic to minify and make the code work on old browsers, but for some reason I feel like there's a better way to do it because I couldn't find any info online about it.

Is that the best way to do it?

Basically, we don't need to minify/transpile external libraries using babel-loader in webpack (as they already support all browsers internally). For these files, you can use script-loader instead of babel-loader.

One alternative way of importing would be by adding these libraries using npm and importing them where ever required. By this approach, webpack includes these libraries where ever required instead of loading it every time which is unnecessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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