WIP (example) Core: Define the `exports` & `module` fields in package.json
Summary
module is needed for Parcel which still doesn't support exports: https://github.com/parcel-bundler/parcel/issues/4155
I prepared this after reading https://nodejs.org/api/packages.html and https://webpack.js.org/guides/package-exports/. Important information is:
- jQuery can be loaded & used both in the browser and in Node.js
- jQuery is stateful so we need to make sure it's not loaded twice by accident (vide the Dual package hazard section from Node.js docs)
- Bundling using popular bundlers (Webpack, Parcel, Vite, Browserify, etc.) should be possible
This draft contains files as they'd exist in a final package. Of course, the final PR would be different, files would be generated during the build and only included in published packages but I included them in the PR so that it can be experimented with.
Ref gh-4592
Checklist
- [ ] New tests have been added to show the fix or feature works
- [ ] Grunt build and unit tests pass locally with these changes
- [ ] If needed, a docs issue/PR was created at https://github.com/jquery/api.jquery.com
An example script showing how it works in Node.js:
'use strict';
// Get a `window` implementation from jsdom and assign it to the global.
import jsdom from 'jsdom';
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
globalThis.window = window;
// Log the jQuery slim version
const jQuerySlim = (await import('jquery/slim')).default;
console.log('jQuery slim version:', jQuerySlim?.fn?.jquery);
// Log the contents of the internal cssExpand array.
const cssExpand = (await import('jquery/src/css/var/cssExpand.js')).default;
console.log('jQuery cssExpand array:', cssExpand);
To run this example, save it as test.js in an npm project, install jsdom as a dependency and link node_modules/jquery to a clone of this branch - and run node test.js in a console.
@guybedford @jkrems @mylesborins could you have a look?
Shouldn't this be put in the 4.0.0 milestone?
@ollie-iterators We have #4592 for tracking purposes; this PR is a POC of what the compiled bundles could look like; the final code will not include any built files and will need code to actually generate them so it will be a different PR.
I created a PR adding exports support & the ESM build at #5255. This WIP is no longer needed, the PR contains all the relevant details with test cases.
One important change from this POC is that I ended up just defining a single entry point for Node.js. This is because our compiled ESM version still only has a default export with the value of module.exports from the regular file - which is just what Node.js does natively if you import a CommonJS module from an ESM one. Using a single file allows to avoid the dual package hazard altogether.