UnderStrap(WordPress)自定义JS添加路径及配置确认
Custom JS Files in UnderStrap (WordPress): Placement, Enqueuing, and Gulp Setup
Great question! Let's break this down clearly since UnderStrap follows a specific asset workflow that's easy to nail once you know the pattern:
File Placement
- Always put custom JS in
src/js/— the rootjs/directory is for compiled output files, not your source code. UnderStrap uses Gulp to process assets from thesrc/folder and spit them into root directories, so any changes you make directly injs/will get overwritten the next time you run a Gulp build. - For better organization, I recommend creating a subfolder like
src/js/custom/to keep your custom scripts separate from default UnderStrap/Bootstrap files.
Enqueuing via inc/enqueue.php
- Yes, you need to enqueue your compiled custom JS file here. This is how WordPress loads scripts properly (avoids conflicts, handles dependencies, etc.). Here's a quick example:
// Enqueue custom script wp_enqueue_script( 'understrap-custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), // Dependencies (adjust based on your script's needs) wp_get_theme()->get( 'Version' ), true // Load in footer (best practice for page performance) ); - Important: Reference the compiled file in the root
js/directory, not the source file insrc/js/.
Modifying gulpfile.js
- You do need to update the Gulp config to include your custom JS files so they get compiled. Open
gulpfile.jsand locate thescriptstask (or thesrcarray for JS processing). - Add your custom file path to the list. For example, if you have
src/js/custom.js, update the JS source like this:const jsSources = [ './src/js/bootstrap.bundle.min.js', './src/js/skip-link-focus-fix.js', './src/js/custom.js' // Add your custom file here ]; - If you're using a subfolder for custom scripts, use a glob pattern like
./src/js/custom/**/*.jsto include all JS files in that directory. - After updating, run
gulp scripts(orgulp watchto auto-compile when you make changes) to generate the compiled file in the rootjs/folder.
Are Your Proposed Steps Correct?
- Short answer: Yes, you're completely on the right track! The key steps you identified (placing source JS in
src/js/, enqueuing viainc/enqueue.php, updatinggulpfile.js) align perfectly with UnderStrap's intended workflow. Just remember to always work in thesrc/directory for source assets, let Gulp handle compilation, and enqueue the final output files.
内容的提问来源于stack exchange,提问作者Wasteland
相关产品推荐
相关产品推荐

