Reputation: 1160
I'm building a WordPress plugin. I have the following in a JavaScript file called demo-one.js:
import WooCommerceRestApi from "https://unpkg.com/@woocommerce/[email protected]/index.js";
alert('Hello!');
class someClass {
constructor() {
alert("Hello again!");
}
}
export default function(){
var mySomeClass = new someClass();
}
... and I find that in my console, I get the following error:
SyntaxError: import not found: default | demo-one.js:1:7
All the information on the export
keyword that I could find online used free-floating values and functions, outside of a class, so I apologize for flying a bit blind.
I was pretty sure that I was correctly defining a default export, but it appears that I'm not. What am I doing wrong here?
Upvotes: 4
Views: 3953
Reputation: 17256
To use import
you have to register that JavaScript as a module:
// Your regular enqueue here
wp_enqueue_script( 'myplugin.js.main', $url, [], $path );
// Add type="module" to your script tag.
// Before: <script src="myscript.js"></script>
// After: <script src="myscript.js" type="module"></script>
add_filter( 'script_loader_tag', function( $tag, $handle, $src ) {
// Replace "myplugin.js.main" with your asset's handler
if ( $handle !== 'myplugin.js.main' ) {
return $tag;
}
return sprintf( '<script src="%s" type="module"></script>', esc_url( $src ) );
}, 10, 3 );
Upvotes: 2