1

I've recently taken the step to refactor all the ever-growing JS code of one of my projects into module logic for better organization. Although working fine so far, one of the caveats I ran into is that several of my scripts are integrated into an userscript which I'm running via ViolentMonkey. @require-ing a script that used any module logic would simply prevent the userscript from running at all.

What can I do to make my userscript run with module logic? I heard people recommending require.js, but I've also seen opinions about AMD not being that great and I don't find the proposed coding style to be very appealing either. Would it still be possible to make it work with javascript native module logic? It's hard for me to make my opinion on this, so any input would be welcome.

I'm running the userscript on firefox exclusively and content-injected. I'm not running any package manager or transpiler, and I would like to keep it that way if possible.

TheMaster
  • 45,448
  • 6
  • 62
  • 85
StrikeAgainst
  • 556
  • 6
  • 23
  • When I was facing this problem, I [decided to use](https://github.com/CertainPerformance/Stack-Exchange-Userscripts/tree/master/Three-Columns/src) Webpack. It's quite trivial to set up and makes things so much more organized, I'd recommend at least trying it out – CertainPerformance May 02 '20 at 23:51
  • I've used Webpack before, but it would require me to set up `npm`, which I'm not too keen about. I'd like to keep it as vanilla as possible, just a personal preference though. – StrikeAgainst May 03 '20 at 01:52
  • If you want to use **native** modules, I think you'll have to inject the script code into the page as a ` – CertainPerformance May 03 '20 at 02:06
  • 1
    (and injecting script elements won't work on many modern sites with restrictive CSP e.g. github) – wOxxOm May 03 '20 at 04:10
  • RequireJS is quite old but works fine, in any browser. But it requires to format file as AMD modules. You can also go for native modules. But that also requires changes in the files, you need to have imports and exports. As mentioned here earlier – Damian Dziaduch May 04 '20 at 11:03
  • @DamianDziaduch Well the change to native modules is what I did beforehand and lead me to the problem in the first place. Userscripts seemingly can't cope with that. I'm trying to work with Webpack now, maybe I can get into it after all... – StrikeAgainst May 05 '20 at 11:53

0 Answers0