简体   繁体   中英

After trying to enqueue several Javascript scripts in my Wordpress PHP file, how can I prevent “cannot use import statement outside a module?”

I'm writing a plugin for my Wordpress php file, which seeks to emulate an HTML file I had previously made, which calls several Javascript in this manner:

<script src="./Controller/myfile.js" type="module" defer></script>

However, with Wordpress, bc I'm not making a simple.html file, I cannot do that directly. I have enqueued scripts, but when I try to go to where these scripts are run, I see Uncaught SyntaxError: Cannot use import statement outside a module and unexpected token: export in the browser console. What do I need to put in my.php file to fix this problem?

The file ./Controller/myfile.js or any other file you enqueue in WP has to be the final output/build of your JS. That means you can't have import statements or anything like that since all code must be on that file. This is because once WP renders your file in <script> , no further processing happens (ie no resolving modules, etc.). I'd recommend using something like Gulpjs to bundle up your source js code and produce a minified build file which you can then enqueue.

Edit:

If your enqueued script doesn't have type="module" , then follow Aioros's comment above and enqueue it properly with module as your type attribute. I'd still recommend getting a bundle since type="module" has limited support developer.mozilla.org modules

When you enqueue your script with wp_enqueue_script() , you end up with a script element like this:

<script src="./Controller/myfile.js"></script>

As you can see, it doesn't have the type="module" attribute, and I imagine that's why you get an error for import . There are a few ways to add it.

I don't know how exactly you're registering/enqueuing the script, but let's pretend it's like this:

wp_enqueue_script("myfile", "Controller/myfile.js");

Then you could add to your plugin a filter like:

function add_type_module_attribute($tag, $handle) {
   if ( $handle !== 'myfile' ) {
      return $tag;
   }
   // needed in case you already have a type='javascript' attribute
   $new_tag = str_replace("type='text/javascript'", '', $tag);
   // adding type='module'
   $new_tag = str_replace(" src", " type='module' defer src", $tag);
   return $new_tag;
}
add_filter('script_loader_tag', 'add_type_module_attribute', 10, 2);

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