momocow / webpack-userscript

A Webpack plugin for userscript projects. 🙈
https://cow.moe/webpack-userscript/
MIT License
200 stars 21 forks source link

How to do code splitting with userscripts? #41

Closed momocow closed 1 year ago

momocow commented 3 years ago

@momocow how would I get this to work with code splitting? Currently all my chunks get appended with .user.jsand the userscript headers when I only want it for the specified entries. Use case is sharing library code between entry userscripts.

_Originally posted by @iamogbz in https://github.com/momocow/webpack-userscript/issues/36#issuecomment-709924679

iamogbz commented 3 years ago

Splitting imports in the userscript to different chunks results in the chunks also suffixed with .user.js not only the entry files.

// webpack.config.js
export default {
  entry: "./scripts",
  optimization: {
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        lib: {
          test: /[\\/]libraries[\\/](.*?)\.ts$/,
          name(module) {/* return lib chunk name */},
      },
    },
  },
  /* ... */
}

The use case for this is publishing shared library files that multiple userscripts can point to import. It would useful to be able to decide what files get affected by the plugin.

I was able to get around this by having two different config files, one for compiling and optimizing and another with the WebpackUserscript plugin for creating the .user.js files. I guess I'm doing some other weird things as being able to specify different header object for each script was needed as well. See oh-my-scripts/webpack.config.ts.

momocow commented 3 years ago

Splitting imports in the userscript to different chunks results in the chunks also suffixed with .user.js not only the entry files.

I got your point.

Currently all .js files in an entry chunk are packed into .user.js files respectively. In a simple use case, there is usually only one file in a chunk.

https://github.com/momocow/webpack-userscript/blob/915cb3c4ccc0770d5da42ed55b482cc0e0b8d171/lib/index.js#L107-L118

It seems that only packing the entry file into an .user.js file can satisfy your use case, am I right?

iamogbz commented 3 years ago

That would work! Although there's still the use case of being able to specify different header objects for different user scripts.

momocow commented 3 years ago

@iamogbz Headers can be specified with a header provider function, which is called before each time a file is packed into an .user.js.

Hope this can meet your requirement, or let me know the detailed use case!

inazuma-bot commented 1 year ago

:tada: This issue has been resolved in version 3.0.0 :tada:

The release is available on:

Your semantic-release bot :package::rocket: