diff --git a/www/content/docs.md b/www/content/docs.md index 171c31f06..1c29b603c 100644 --- a/www/content/docs.md +++ b/www/content/docs.md @@ -152,36 +152,79 @@ For npm-style build systems, you can install htmx via [npm](https://www.npmjs.co npm install htmx.org@2.0.1 ``` -After installing, you’ll need to use appropriate tooling to use `node_modules/htmx.org/dist/htmx.js` (or `.min.js`). -For example, you might bundle htmx with some extensions and project-specific code. +After installing, you’ll need to use appropriate tooling to use `node_modules/htmx.org/dist/htmx[.esm, .cjs, .amd].js` (or `.min.js`). -### Webpack +In the simplest case all you need to do is to add this import to your entry point (like `index.js`) +```js +import 'htmx.org'; +``` + +However, you will probably need the global `htmx` variable, which gives your code access to methods like +`htmx.onLoad` and allow you to use npm-installed htmx plugins. You can use one of the following solutions +to achieve this. -If you are using webpack to manage your javascript: -* Install `htmx` via your favourite package manager (like npm or yarn) -* Add the import to your `index.js` +#### Global variable + +Create a local `htmx.js` with the following content: ```js -import 'htmx.org'; +import htmx from "htmx.org"; +window.htmx = htmx; ``` -If you want to use the global `htmx` variable (recommended), you need to inject it to the window scope: +Import this file in your entry point (like `index.js`): + +```js +import './htmx.js'; + +// now you can import extensions +import 'htmx-ext-debug/debug.js'; +// and use htmx methods +htmx.onLoad((content) => { + console.log('Hello') +}); +``` + +#### Webpack -* Create a custom JS file -* Import this file to your `index.js` (below the import from step 2) +If you are using [webpack](https://webpack.js.org) to manage your javascript, the better option is +to add the following to your `webpack.config.js` ```js -import 'path/to/my_custom.js'; +import webpack from 'webpack'; + +/** @type {import("webpack").Configuration} */ +export default { + entry: './src/index.js', + //[...] + plugins: [ + new webpack.ProvidePlugin({ + htmx: 'htmx.org', + }), + ], +}; ``` -* Then add this code to the file: +#### Vite + +If you are using [Vite](https://vitejs.dev) to manage your javascript, the better option is +to add the following to your [vite.config.js](https://vitejs.dev/guide/backend-integration.html): ```js -window.htmx = require('htmx.org'); +import inject from '@rollup/plugin-inject'; + +export default defineConfig({ + build: {...}, + plugins: [ + inject({ + htmx: 'htmx.org', + }), + ], +}) ``` -* Finally, rebuild your bundle +Finally, rebuild your bundle. ## AJAX