Hi everyone,
I’m building a Chrome extension in vanilla JS, HTML, and CSS. The problem is that I’m having trouble using external libraries (e.g. Material Design components) since I’m unable to follow the usage instructions provided in the documentation. Things like import or require always throw an error.
As a concrete example, I’m trying to use Material’s switch component, but in order for it to actually function, I need to add some Javascript and this is where I hit a brick wall since non of the options seem to apply to me.
What is generally the right way to set up a project like this? It seems like such an unnecessary hassle everytime I try to reference or use some external component. Should I just use something like React?
You can find the whole project on GitHub.
Guess you could download/clone the repo, grab the JS file you need and add it into your extension folder.
It’s a bit “old school” but I guess it’s doable
Then if you want external libraries, you just import them Use this to find them and check they work (just directly from NPM or even Unpkg won’t work for most things, the ecosystem is only moving veeeeeeeeerrrrrrrrrry gradually towards ES6 modules as standard):
Note that importrequires the file type, you can’t do import foo from "./foo-module" it has to be "./foo-module.js". Being allowed to miss off the qualifier is just a module bundler “feature” to make them work visually like Node CommonJS modules, it isn’t part of the JS spec at all
Referencing the script as a module enables import. However, I couldn’t get the import form Skypack to work. I found Material’s switch component on Skypack here. I’m able to run it in the browser, but the Chrome extension generates the following error:
Ah, I just specified how it would work normally, I’ve never built a Chrome extension and assumed they worked the same way. Have you read how Chrome extensions work? They can’t reference external scripts at all, it has to be contained in a single webpage, so you can’t do what you were trying to do anyway, you have to really package it up into a single script
Ah sorry I meant NPM. Issue you’ll have is that if it hasn’t been written as JS modules then it won’t work as an module, so you’ll need to use a bundling tool like Rollup that emits a standalone JS module. This isn’t trivial and it’s easy to make errors, so it’s much easier to just use Webpack/Rollup to build your whole project and have it emit a single bundle with all your code