diff options
Diffstat (limited to 'examples/snowpack/src/pages/reference')
8 files changed, 1092 insertions, 0 deletions
diff --git a/examples/snowpack/src/pages/reference/cli-command-line-interface.md b/examples/snowpack/src/pages/reference/cli-command-line-interface.md new file mode 100644 index 000000000..338eee415 --- /dev/null +++ b/examples/snowpack/src/pages/reference/cli-command-line-interface.md @@ -0,0 +1,41 @@ +--- +layout: ../../layouts/content.astro +title: Command Line API +description: The Snowpack Command Line tool's API, commands, and flags. +--- + +### Commands + +``` +$ snowpack --help + +snowpack init Create a new project config file. +snowpack dev Develop your app locally. +snowpack build Build your app for production. + +... +``` + +### Flags + +```bash +# Show helpful info +$ snowpack --help + +# Show additional debugging logs +$ snowpack --verbose + +# {devOptions: {open: 'none'}} +$ snowpack dev --open none + +# {buildOptions: {clean: true/false}} +$ snowpack build --clean +$ snowpack build --no-clean +``` + +**CLI flags will be merged with (and take priority over) your config file values.** Every config value outlined below can also be passed as a CLI flag. Additionally, Snowpack also supports the following flags: + +- **`--config [path]`** Set the path to your project config file. +- **`--help`** Show this help. +- **`--version`** Show the current version. +- **`--reload`** Clear the local cache. Useful for troubleshooting installer issues. diff --git a/examples/snowpack/src/pages/reference/common-error-details.md b/examples/snowpack/src/pages/reference/common-error-details.md new file mode 100644 index 000000000..c25be136d --- /dev/null +++ b/examples/snowpack/src/pages/reference/common-error-details.md @@ -0,0 +1,72 @@ +--- +layout: ../../layouts/content.astro +title: Common Error Details +description: How to troubleshoot common issues and error messagesm, plus our resources for getting help. +--- + +This page details several common issues and error messages. For further help we have an active [GitHub Discussion forum](https://github.com/snowpackjs/snowpack/discussions)and [Discord](https://discord.gg/snowpack). Developers and community contributors frequently answer questions on both. + +### No such file or directory + +``` +ENOENT: no such file or directory, open …/node_modules/csstype/index.js +``` + +This error message would sometimes occur in older versions of Snowpack. + +**To solve this issue:** Upgrade to Snowpack `v2.6.0` or higher. If you continue to see this unexpected error in newer versions of Snowpack, please file an issue. + +### Package exists but package.json "exports" does not include entry + +Node.js recently added support for a package.json "exports" entry that defines which files you can and cannot import from within a package. Preact, for example, defines an "exports" map that allows you to to import "preact/hooks" but not "preact/some/custom/file-path.js". This allows packages to control their "public" interface. + +If you see this error message, that means that you've imported a file path not allowed in the export map. If you believe this to be an error, reach out to the package author to request the file be added to their export map. + +### Uncaught SyntaxError: The requested module '/\_snowpack/pkg/XXXXXX.js' does not provide an export named 'YYYYYY' + +If you are using TypeScript, this error could occur if you are importing something that only exists in TypeScript (like a type or interface) and doesn't actually exist in the final JavaScript code. This issue is rare since our built-in TypeScript support will automatically extract and remove only type-only imports. + +**To solve:** Make sure to use `import type { MyInterfaceName }` instead. + +This error could also appear if named imports are used with older, Common.js npm packages. Thanks to improvements in our package scanner this is no longer a common issue for most packages. However, some packages are written or compiled in a way that makes automatic import scanning impossible. + +**To solve:** Use the default import (`import pkg from 'my-old-package'`) for legacy Common.js/UMD packages that cannot be analyzed. Or, add the package name to your `packageOptions.namedExports` configuration for runtime import scanning. + +```js +// snowpack.config.js +{ + "packageOptions": { + "namedExports": ["@shopify/polaris-tokens"] + } +} +``` + +### Installing Non-JS Packages + +When installing packages from npm, you may encounter some file formats that can run only with additional parsing/processing. First check to see if there is a [Snowpack plugin for the type of file](/plugins). + +Because our internal installer is powered by Rollup, you can also add Rollup plugins to your [Snowpack config](/reference/configuration) to handle these special, rare files: + +```js +/* snowpack.config.js */ +module.exports = { + rollup: { + plugins: [require('rollup-plugin-sass')()], + }, +}; +``` + +Refer to [Rollup’s documentation on plugins](https://rollupjs.org/guide/en/#using-plugins) for more information. + +### RangeError: Invalid WebSocket frame: RSV1 must be clear + +**To solve this issue:** Use any other port than `8080` for the dev server. To do so, specify a port in your [Snowpack config](/reference/configuration): + +```js +/* snowpack.config.js */ +module.exports = { + devOptions: { + port: 3000, + }, +}; +``` diff --git a/examples/snowpack/src/pages/reference/configuration.md b/examples/snowpack/src/pages/reference/configuration.md new file mode 100644 index 000000000..d1ed2fc34 --- /dev/null +++ b/examples/snowpack/src/pages/reference/configuration.md @@ -0,0 +1,473 @@ +--- +layout: ../../layouts/content.astro +title: snowpack.config.js +description: The Snowpack configuration API reference. +--- + +```js +// Example: snowpack.config.js +// The added "@type" comment will enable TypeScript type information via VSCode, etc. + +/** @type {import("snowpack").SnowpackUserConfig } */ +module.exports = { + plugins: [ + /* ... */ + ], +}; +``` + +To generate a basic configuration file scaffold in your Snowpack project run `snowpack init`. + +## root + +**Type**: `string` +**Default**: `/` + +Specify the root of a project using Snowpack. (Previously: `config.cwd`) + +## workspaceRoot + +**Type**: `string` + +Specify the root of your workspace or monorepo, if you are using one. When configured, Snowpack will treat any sibling packages in your workspace like source files, and pass them through your unbundled Snowpack build pipeline during development. This allows for fast refresh, HMR support, file change watching, and other dev improvements when working in monorepos. + +When you build your site for production, symlinked packages will be treated like any other package, bundled and tree-shaken into single files for faster loading. + +## install + +Deprecated! Moved to `packageOptions.knownEntrypoints` + +## extends + +**Type**: `string` + +Inherit from a separate "base" config. + +Can be a relative file path, an npm package, or a file within an npm package. Your configuration will be merged on top of the extended base config. + +## exclude + +**Type**: `string[]` +**Default**: `['**/node_modules/**/*']` + +Exclude any files from the Snowpack pipeline. + +Supports glob pattern matching. + +## mount + +``` +mount: { + [path: string]: string | {url: string, resolve: boolean, static: boolean} +} +``` + +Mount local directories to custom URLs in your built application. + +- `mount.url` | `string` | _required_ : The URL to mount to, matching the string in the simple form above. +- `mount.static` | `boolean` | _optional_ | **Default**: `false` : If true, don't build files in this directory. Copy and serve them directly from disk to the browser. +- `mount.resolve` | `boolean` | _optional_ | **Default**: `true`: If false, don't resolve JS & CSS imports in your JS, CSS, and HTML files. Instead send every import to the browser, as written. +- + +Example: + +```js +// snowpack.config.js +// Example: Basic "mount" usage +{ + "mount": { + "src": "/dist", + "public": "/" + } +} +``` + +You can further customize this the build behavior for any mounted directory by using the expanded object notation: + +```js +// snowpack.config.js +// Example: expanded object notation "mount" usage +{ + "mount": { + // Same behavior as the "src" example above: + "src": {url: "/dist"}, + // Mount "public" to the root URL path ("/*") and serve files with zero transformations: + "public": {url: "/", static: true, resolve: false} + } +} +``` + +## alias + +**Type**: `object` (package: package or path) + +Configure import aliases for directories and packages. + +Note: In an older version of Snowpack, all mounted directories were also available as aliases by **Default**. As of Snowpack 2.7, this is no longer the case and no aliases are defined by **Default**. + +```js +// snowpack.config.js +// Example: alias types +{ + alias: { + // Type 1: Package Import Alias + "lodash": "lodash-es", + "react": "preact/compat", + // Type 2: Local Directory Import Alias (relative to cwd) + "components": "./src/components" + "@app": "./src" + } +} +``` + +## plugins + +**Type**: `array` containing pluginName `string` or an array [`pluginName`, {`pluginOptions`} + +Enable Snowpack plugins and their options. + +Also see our [Plugin guide](/guides/plugins) + +```js +// snowpack-config.js +// Example: enable plugins both simple and expanded +{ + plugins: [ + // Simple format: no options needed + 'plugin-1', + // Expanded format: allows you to pass options to the plugin + ['plugin-2', { 'plugin-option': false }], + ]; +} +``` + +## devOptions + +**Type**: `object` (option name: value) + +Configure the Snowpack dev server. + +### devOptions.secure + +**Type**: `boolean` +**Default**: `false` + +Toggles whether Snowpack dev server should use HTTPS with HTTP2 enabled. + +### devOptions.hostname + +**Type**: `string` +**Default**: `localhost` + +The hostname that the dev server is running on. Snowpack uses this information to configure the HMR websocket and properly open your browser on startup (see: [`devOptions.open`](#devoptions.open)). + +### devOptions.port + +**Type**: `number` +**Default**: `8080` + +The port the dev server runs on. + +### devOptions.fallback + +**Type**: `string` +**Default**: `"index.html"` + +The HTML file to serve for non-resource routes. + +When using the Single-Page Application (SPA) pattern, this is the HTML "shell" file that gets served for every (non-resource) user route. + +⚠️ Make sure that you configure your production servers to serve this. + +### devOptions.open + +**Type**: `string` +**Default**: `"**Default**"` + +Configures how the dev server opens in the browser when it starts. + +Any installed browser, e.g., "chrome", "firefox", "brave". Set "none" to disable. + +### devOptions.output + +**Type**: `"stream" | "dashboard"` +**Default**: `"dashboard"` + +Set the output mode of the `dev` console: + +- `"dashboard"` delivers an organized layout of console output and the logs of any connected tools. This is recommended for most users and results in the best logging experience. +- `"stream"` is useful when Snowpack is run in parallel with other commands, where clearing the shell would clear important output of other commands running in the same shell. + +### devOptions.hmr + +**Type**: `boolean` +**Default**: `true` + +Toggles HMR on the Snowpack dev server. + +### devOptions.hmrDelay + +**Type**: `number` (milliseconds) +**Default**: `0` + +Milliseconds to delay HMR-triggered browser update. + +### devOptions.hmrPort + +**Type**: `number` +**Default**: [`devOptions.port`](#devoptions.port) + +The port where Snowpack's HMR Websocket runs. + +### devOptions.hmrErrorOverlay + +**Type**: `boolean` +**Default**: `true` + +Toggles a browser overlay that displays JavaScript runtime errors when running HMR. + +### devOptions.out + +**Type**: `string` +**Default**: `"build"` + +_NOTE:_ Deprecated, see `buildOptions.out`. + +## installOptions + +**Type**: `object` + +_NOTE:_ Deprecated, see `packageOptions`. + +## packageOptions + +**Type**: `object` + +Configure how npm packages are installed and used. + +### packageOptions.external + +**Type**: `string[]` +**Example**: `"external": ["fs"]` + +Mark some imports as external. Snowpack will ignore these imports and leave them as-is in your final build. + +This is an advanced feature: Bare imports are not supported in any major browser, so an ignored import will usually fail when sent directly to the browser. This will most likely fail unless you have a specific use-case that requires it. + +### packageOptions.source + +**Type**: `"local" | "remote"` +**Default**: `"local"` +**Example**: `"source": "local"` + +Your JavaScript npm packages can be consumed in two different ways: **local** and **remote**. Each mode supports a different set of package options. You can choose between these two different modes by setting the `packageOptions.source` property. + +### packageOptions.source=local + +Load your dependencies from your local `node_modules/` directory. Install and manage your dependencies using `npm` (or any other npm-ready package manager) and a project `package.json` file. + +This is traditional Snowpack behavior matching Snowpack v2. This mode is recommended for anyone already using npm to manage their frontend dependencies. + +#### packageOptions.knownEntrypoints + +**Type**: `string[]` + +Known dependencies to install with Snowpack. Used for installing packages any dependencies that cannot be detected by our automatic import scanner (ex: package CSS files). + +#### packageOptions.polyfillNode + +**Type**: `boolean` +**Default**: `false` + +This will automatically polyfill any Node.js dependencies as much as possible for the browser + +Converts packages that depend on Node.js built-in modules (`"fs"`, `"path"`, `"url"`, etc.). You can see the full list of supported polyfills at the [rollup-plugin-node-polyfills documentation](https://github.com/ionic-team/rollup-plugin-node-polyfills) + +If you'd like to customize this polyfill behavior, you can provide your own Rollup plugin for the installer: + +```js +// Example: If `--polyfill-node` doesn't support your use-case, you can provide your own custom Node.js polyfill behavior +module.exports = { + packageOptions: { + polyfillNode: false, + rollup: { + plugins: [require('rollup-plugin-node-polyfills')({crypto: true, ...})], + }, + }, +}; +``` + +When `source="remote"`, Node.js polyfills are always provided. Configuring this option is only supported in `source="local"` mode. + +#### packageOptions.env + +**Type**: `{[ENV_NAME: string]: (string true)}` + +Sets a `process.env.` environment variable inside the installed dependencies. + +If set to true (ex: `{NODE_ENV: true}` or `--env NODE_ENV`) this will inherit from your current shell environment variable. Otherwise, set to a string (ex: `{NODE_ENV: 'production'}` or `--env NODE_ENV=production`) to set the exact value manually. + +This option is only supported in `source="local"` mode. `source="remote"` does not support this feature yet. + +#### packageOptions.packageLookupFields + +**Type**: `string[]` +**Example**: `"packageLookupFields": ["svelte"]` + +Set custom lookup fields for dependency `package.json` file entrypoints, in addition to the defaults like "module", "main", etc. + +This option is only supported in `source="local"` mode. `source="remote"` does not support this feature yet. + +#### packageOptions.packageExportLookupFields + +**Type**: `string[]` +**Example**: `"packageExportLookupFields": ["svelte"]` + +Set custom lookup fields for dependency `package.json` ["exports" mappings.](https://nodejs.org/api/packages.html#packages_package_entry_points) + +This option is only supported in `source="local"` mode. `source="remote"` does not support this feature yet. + +#### packageOptions.rollup + +**Type**: `Object` + +Allows customization of Snowpack's internal Rollup configuration. + +Snowpack uses Rollup internally to install your packages. This `rollup` config option gives you deeper control over the internal Rollup configuration that we use. + +- packageOptions.rollup.plugins | `RollupPlugin[]` - Provide an array of custom Rollup plugins that will run on every installed package. Useful for dealing with non-standard file types in your npm packages. +- packageOptions.rollup.dedupe | `string[]` - If needed, deduplicate multiple versions/copies of a packages to a single one. This helps prevent issues with some packages when multiple versions are installed from your node_modules tree. See [rollup-plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve#usage) for more documentation. +- packageOptions.rollup.context | `string` - Specify top-level `this` value. Useful to silence install errors caused by legacy common.js packages that reference a top-level this variable, which does not exist in a pure ESM environment. Note that the `'THIS_IS_UNDEFINED'` warning ("'this' keyword is equivalent to 'undefined' ... and has been rewritten") is silenced by default, unless `--verbose` is used. + +This option is only supported in `source="local"` mode. `source="remote"` does not support custom Rollup install options. + +### packageOptions.source=remote + +Enable streaming package imports. Load dependencies from our remote CDN. Manage your dependencies using `snowpack` and a project `snowpack.deps.json` file. + +[Learn more about Streaming Remote Imports](/guides/streaming-imports). + +#### packageOptions.origin + +**Type**: `string` +**Default**: `https://pkg.snowpack.dev` + +The remote origin to import packages from. When you import a new package, Snowpack will fetch those resources from this URL. + +Currently, the origin must implement a specific response format that Snowpack can parse for ESM. In future versions of Snowpack we plan to add support for custom CDNs and import origins. + +#### packageOptions.cache + +**Type**: `string` +**Default**: `.snowpack` + +The location of your project cache folder, relative to the project root. Snowpack will save cached data to this folder. For example, if `packageOptions.types` is set to true, Snowpack will save TypeScript types to a `types` directory within this folder. + +#### packageOptions.types + +**Type**: `boolean` +**Default**: `false` + +If true, Snowpack will download TypeScript types for every package. + +## buildOptions + +**Type**: `object` (option name: value) + +Configure your final build. + +### buildOptions.out + +**Type**: `string` +**Default**: `"build"` + +The local directory that we output your final build to. + +### buildOptions.baseUrl + +**Type**: `string` +**Default**: `/` + +In your HTML, replace all instances of `%PUBLIC_URL%` with this + +Inspired by the same [Create React App](https://create-react-app.dev/docs/using-the-public-folder/) concept. This is useful if your app will be deployed to a subdirectory. + +### buildOptions.clean + +**Type**: `boolean` +**Default**: `true` + +Set to `false` to prevent Snowpack from deleting the build output folder (`buildOptions.out`) between builds. + +### buildOptions.webModulesUrl + +_NOTE:_ Deprecated, see `buildOptions.metaUrlPath`. + +### buildOptions.metaDir + +_NOTE:_ Deprecated, see `buildOptions.metaUrlPath`. + +### buildOptions.metaUrlPath + +**Type**: `string` +**Default**: `_snowpack` + +Rename the default directory for Snowpack metadata. In every build, Snowpack creates meta files for loading things like [HMR](/concepts/hot-module-replacement), [Environment Variables](/reference/environment-variables), and your built npm packages. + +When you build your project, this will be a path on disk relative to the `buildOptions.out` directory. + +### buildOptions.sourcemap + +**Type**: `boolean` +**Default**: `false` + +Generates source maps. + +**_Experimental:_** Still in progress, you may encounter some issues when using source maps until this support is finalized. + +### buildOptions.watch + +**Type**: `boolean` +**Default**: `false` + +Run Snowpack's build pipeline through a file watcher. This option works best for local development when you have a custom frontend server (ex: Rails, PHP, etc.) and the Snowpack dev server cannot be used. + +### buildOptions.htmlFragments + +**Type**: `boolean` +**Default**: `false` + +Toggles whether HTML fragments are transformed like full HTML pages. + +HTML fragments are HTML files not starting with "\<!doctype html\>". + +### buildOptions.jsxFactory + +**Type**: `string` +**Default**: `React.createElement` (or `h` if Preact import is detected) + +Set the name of the function used to create JSX elements. + +### buildOptions.jsxFragment + +**Type**: `string` +**Default**: `React.Fragment` (or `Fragment` if Preact import is detected) + +Set the name of the function used to create JSX fragments. + +## testOptions + +Configure your tests. + +### testOptions.files + +**Type**: `string[]` +**Default**: `["__tests__/**/*", "**/*.@(spec|test).*"]` + +Specifies your test files. If `NODE_ENV` is set to "test", Snowpack includes these files in your site build and scan them for installable dependencies. Otherwise, Snowpack excludes these files. + +## experiments + +**Type**: `object` (option name: value) + +This section is currently empty! In the future, this section may be used for experimental and not yet finalized. diff --git a/examples/snowpack/src/pages/reference/environment-variables.md b/examples/snowpack/src/pages/reference/environment-variables.md new file mode 100644 index 000000000..1a4c40794 --- /dev/null +++ b/examples/snowpack/src/pages/reference/environment-variables.md @@ -0,0 +1,58 @@ +--- +layout: ../../layouts/content.astro +title: Environment Variables +description: Using environment variables with Snowpack +--- + +For your safety, Snowpack supports only environment variables which begin with `SNOWPACK_PUBLIC_*`. We do this because everything in your web application is sent to the browser, and we don't want you to accidentally share sensitive keys/env variables with your public web application. Prefixing your frontend web env variables with `SNOWPACK_PUBLIC_` is a good reminder that they will be shared with the world. + +## Setting environment variables + +You can set environment variables with snowpack in three different ways: + +### Option 1: CLI + +Set environment variables when you run the snowpack CLI: + +```bash +SNOWPACK_PUBLIC_API_URL=api.google.com snowpack dev +``` + +### Option 2: Config file + +Set environment variables by adding to `process.env.*` at the top of your `snowpack.config.js` file. + +```js +// snowpack.config.js +process.env.SNOWPACK_PUBLIC_API_URL = 'api.google.com'; +// ...rest of config +``` + +Note that your application won't _read_ these environment variables from `process.env`, but variables that are set here will be available on `import.meta.env` (see below). + +### Option 3: Plugin + +Use a plugin such as [plugin-dotenv](https://www.npmjs.com/package/@snowpack/plugin-dotenv) to load environment variables from a `.env` file. + +## Reading environment variables + +You can read environment variables directly in your web application via `import.meta.env`. If you've ever used `process.env` in Create React App or any Webpack application, this behaves exactly the same. + +```js +// `import.meta.env` - Read process.env variables in your web app +fetch(`${import.meta.env.SNOWPACK_PUBLIC_API_URL}/users`).then(...) + +// Supports destructuring as well: +const {SNOWPACK_PUBLIC_API_URL} = import.meta.env; +fetch(`${SNOWPACK_PUBLIC_API_URL}/users`).then(...) + +// Instead of `import.meta.env.NODE_ENV` use `import.meta.env.MODE` +if (import.meta.env.MODE === 'development') { + // ... +``` + +`import.meta.env.MODE` and `import.meta.env.NODE_ENV` are also both set to the current `process.env.NODE_ENV` value, so that you can change app behavior based on dev vs. build. The env value is set to `development` during `snowpack dev`, and `production` during `snowpack build`. Use this in your application instead of `process.env.NODE_ENV`. + +You can also use environment variables in HTML files. All occurrences of `%SNOWPACK_PUBLIC_*%`, `%PUBLIC_URL%`, and `%MODE%` will be replaced at build time. + +**Remember:** that these env variables are statically injected into your application for everyone at **build time**, and not runtime. diff --git a/examples/snowpack/src/pages/reference/hot-module-replacement.md b/examples/snowpack/src/pages/reference/hot-module-replacement.md new file mode 100644 index 000000000..0b95cebf9 --- /dev/null +++ b/examples/snowpack/src/pages/reference/hot-module-replacement.md @@ -0,0 +1,20 @@ +--- +layout: ../../layouts/content.astro +title: Hot Module Replacement (HMR) API +description: Snowpack implements HMR via the esm-hmr spec, an attempted standard for ESM-based Hot Module Replacement (HMR). +--- + +Snowpack implements HMR via the [esm-hmr](https://github.com/pikapkg/esm-hmr) spec, an attempted standard for ESM-based Hot Module Replacement (HMR). + +```js +// HMR Code Snippet Example +if (import.meta.hot) { + import.meta.hot.accept(({ module }) => { + // Accept the module, apply it into your application. + }); +} +``` + +Full API Reference: [snowpack/esm-hmr on GitHub](https://github.com/snowpackjs/esm-hmr) + +[Learn more](/concepts/hot-module-replacement) about HMR, Fast Refresh, and how it's meant to work in Snowpack. diff --git a/examples/snowpack/src/pages/reference/javascript-interface.md b/examples/snowpack/src/pages/reference/javascript-interface.md new file mode 100644 index 000000000..ad3048240 --- /dev/null +++ b/examples/snowpack/src/pages/reference/javascript-interface.md @@ -0,0 +1,198 @@ +--- +layout: ../../layouts/content.astro +title: JavaScript API +description: Snowpack's JavaScript API is for anyone who wants to integrate with some custom build pipeline or server-side rendering engine. +--- + +Most users will interact with Snowpack via the [command-line](/reference/cli-command-line-interface) interface (CLI). However, Snowpack also ships a JavaScript API for anyone to build on top of. + +This page contains reference information on Snowpack's public API and all related data types. A full set of all data types defined within the project (public and private) can be found in [the package's `types.d.ts` file](https://unpkg.com/browse/snowpack@3.0.10/lib/types.d.ts). + +### createConfiguration() + +`createConfiguration(config?: SnowpackUserConfig) => SnowpackConfig` + +```js +import {createConfiguration} from 'snowpack'; +const config = createConfiguration({...}); +``` + +Almost everything that you do with Snowpack requires a configuration object. Snowpack is designed to work with zero config, and the `config` argument that this function takes can be full, empty, or only contain a couple of properties. The rest of the configuration object will be filled out with Snowpack's usual set of defaults, outlined in our [snowpack.config.js documentation.](/reference/configuration). + +The easiest way to think about the difference is that `SnowpackUserConfig` is the externally-documented configuration format, and `SnowpackConfig` is our internal representation with all optional/undefined values populated with the actual defaults. + +### loadConfiguration() + +`loadConfiguration(overrides?: SnowpackUserConfig, configPath?: string | undefined) => Promise<SnowpackConfig>` + +```js +import {loadConfiguration} from 'snowpack'; +const config = loadConfiguration({...}, '/path/to/snowpack.config.js'); +``` + +Similar to `createConfiguration`, but this function will actually check the file system to load a configuration file from disk. + +All paths within that configuration file are relative to the file itself. + +### startServer() + +`function startServer({config: SnowpackUserConfig}) => Promise<SnowpackDevServer>` + +```js +import {startServer} from 'snowpack'; +const config = createConfiguration({...}); +const server = await startServer({config}); // returns: SnowpackDevServer +``` + +Start a new Snowpack dev server instance. This is the equivalent of running `snowpack dev` on the command line. + +Once started, you can load files from your dev server and Snowpack will build them as requested. This is an important feature to understand: Snowpack's dev server does zero file building on startup, and instead builds files only once they are requested via the server's `loadUrl` method. + +### SnowpackDevServer + +#### SnowpackDevServer.port + +The port that the server is listening on. + +#### SnowpackDevServer.loadUrl() + +`loadUrl(reqUrl: string, opt?: {isSSR?: boolean; allowStale?: boolean; encoding?: string}): Promise<LoadResult<Buffer | string>>;` + +```ts +const server = await startServer({config}); +const {contents} = server.loadUrl('/dist/index.js', {...}); +``` + +Load a file and return the result. On the first request of a URL, this will kick off a build that will then be cached for all future requests during the life of the server. + +You can pass `allowStale: true` to enable Snowpack's cold cache for cached results from past sessions. However, Snowpack provides no guarentee on the freshness of the cold-cache data. + +#### SnowpackDevServer.getUrlForFile() + +`getUrlForFile(fileLoc: string) => string | null;` + +```ts +const server = await startServer({config}); +const fileUrl = server.getUrlForFile('/path/to/index.jsx'); +const {contents} = server.loadUrl(fileUrl, {...}); +``` + +A helper function to find the final hosted URL for any source file. Useful when combined with `loadUrl`, since you may only know a file's location on disk without knowing it's final hosted URL. + +#### SnowpackDevServer.sendResponseError() + +`sendResponseError(req: http.IncomingMessage, res: http.ServerResponse, status: number) => void;` + +A helper function to send an error response in a server response handler. Useful when integrating Snowpack with Express, Koa, or any other Node.js server. + +#### SnowpackDevServer.onFileChange() + +`onFileChange({filePath: string}) => void;` + +Listen for watched file change events. Useful for situations where you might want to watch the file system for changes yourself, and can save overhead/performance by hooking into our already-running watcher. + +#### SnowpackDevServer.shutdown() + +`shutdown() => Promise<void>;` + +```ts +const server = await startServer({ config }); +await server.shutdown(); +``` + +Shut down the Snowpack dev server. Cleanup any long-running commands, file watchers, etc. + +#### SnowpackDevServer.getServerRuntime() + +`getServerRuntime({invalidateOnChange?: boolean}) => ServerRuntime;` + +```ts +const server = await startServer({ config }); +const runtime = server.getServerRuntime(); +const { helloWorld } = (await runtime.importModule('/dist/index.js')).exports; +helloWorld(); +``` + +Returns an ESM Server Runtime that lets Node.js import modules directly out of Snowpack's build cache. Useful for SSR, test running frontend code, and the overall unification of your build pipeline. + +For more information, check out our guide on [Server-Side Rendering](/guides/server-side-render) using the `getServerRuntime()` API. + +#### ServerRuntime + +```ts +interface ServerRuntime { + /** Import a Snowpack-build JavaScript file into Node.js. */ + importModule(url: string) => Promise<ServerRuntimeModule>; + /** Invalidate a module in the internal runtime cache. */ + invalidateModule(url: string) => void; +} +``` + +#### ServerRuntimeModule + +```ts +interface ServerRuntimeModule { + /** The imported module. */ + exports: any; + /** References to all internal CSS imports. Useful for CSS extraction. */ + css: string[]; +} +``` + +### build() + +`build({config: SnowpackUserConfig}) => Promise<SnowpackBuildResult>` + +```js +import {build} from 'snowpack'; +const config = createConfiguration({...}); +const {result} = await build({config}); // returns: SnowpackBuildResult +``` + +#### SnowpackBuildResult.result + +An in-memory manifest of all build inputs & output files. + +#### SnowpackBuildResult.shutdown + +In `--watch` mode, the `build()` function will resolve but the build itself will continue. Use this function to shut down the build watcher. + +In normal build mode (non-watch mode) this function will throw with a warning. + +#### SnowpackBuildResult.onFileChange + +In `--watch` mode, the `build()` function will resolve but the build itself will continue. Use this function to respond to file change events without having to spin up your own file watcher. + +In normal build mode (non-watch mode) this function will throw with a warning. + +### getUrlForFile() + +`getUrlForFile(fileLoc: string, config: SnowpackConfig) => string | null` + +```js +import { getUrlForFile } from 'snowpack'; +const fileUrl = getUrlForFile('/path/to/file.js', config); +``` + +A helper function to find the final hosted URL for any source file. Useful when combined with `loadUrl`, since you may only know a file's location on disk without knowing it's final hosted URL. + +Similar to `SnowpackDevServer.getUrlForFile()`, but requires a second `config` argument to inform the result. + +### clearCache() + +`clearCache() => Promise<void>` + +```js +import { clearCache } from 'snowpack'; +await clearCache(); +``` + +Equivalent of using the `--reload` flag with the `snowpack` CLI. Clears all cached data in Snowpack. Useful for troubleshooting, or clearing the cache after making some change that Snowpack couldn't detect. + +### logger + +```js +import { logger } from 'snowpack'; +``` + +You can control Snowpack's internal logger directly by importing it. Note that this is an advanced feature not needed for most users. Instead, use the `verbose` config option to enable debug logging and control log message verbosity. diff --git a/examples/snowpack/src/pages/reference/plugins.md b/examples/snowpack/src/pages/reference/plugins.md new file mode 100644 index 000000000..3e38f2b6e --- /dev/null +++ b/examples/snowpack/src/pages/reference/plugins.md @@ -0,0 +1,111 @@ +--- +layout: ../../layouts/content.astro +title: Plugin API +description: The Snowpack Plugin API and how to use it. +--- + +Looking to get started writing your own plugin? Check out our [Plugin Guide](/guides/plugins) for an overview of how plugins work and a walk-through to help you create your own. + +Looking for a good summary? Check out our ["SnowpackPlugin" TypeScript definition](https://github.com/snowpackjs/snowpack/blob/main/snowpack/src/types.ts#L130) for a fully documented and up-to-date overview of the Plugin API and all supported options. + +### Overview + +```js +// my-first-snowpack-plugin.js +module.exports = function (snowpackConfig, pluginOptions) { + return { + name: 'my-first-snowpack-plugin', + config() { + console.log('Success!'); + }, + }; +}; + +// To use this plugin, add it to your snowpack.config.js: +// +// "plugins": [ +// ["./my-first-snowpack-plugin.js", {/* pluginOptions */ }] +// ] +``` + +A **Snowpack Plugin** is an object interface that lets you customize Snowpack's behavior. Snowpack provides different hooks for your plugin to connect to. For example, you can add a plugin to handle Svelte files, optimize CSS, convert SVGs to React components, run TypeScript during development, and much more. + +Snowpack's plugin interface is inspired by [Rollup](https://rollupjs.org/). If you've ever written a Rollup plugin before, then hopefully these concepts and terms feel familiar. + +### Lifecycle Hooks + +#### config() + +```js +config(snowpackConfig) { + // modify or read from the Snowpack configuration object +} +``` + +Use this hook to read or make changes to the completed Snowpack configuration object. This is currently the recommended way to access the Snowpack configuration, since the one passed to the top-level plugin function is not yet finalized and may be incomplete. + +#### load() + +Load a file from disk and build it for your application. This is most useful for taking a file type that can't run in the browser (TypeScript, Sass, Vue, Svelte) and returning JS and/or CSS. It can even be used to load JS/CSS files directly from disk with a build step like Babel or PostCSS. + +#### transform() + +Transform a file's contents. Useful for making changes to all types of build output (JS, CSS, etc.) regardless of how they were originally loaded from disk. + +#### run() + +Run a CLI command, and connect it's output into the Snowpack console. Useful for connecting tools like TypeScript. + +#### optimize() + +Snowpack’s bundler plugin API is still experimental and may change in a future release. See our official bundler plugins for an example of using the current interface: + +- Example: [@snowpack/plugin-webpack](https://github.com/snowpackjs/snowpack/tree/main/plugins/plugin-webpack) +- Example: [snowpack-plugin-rollup-bundle](https://github.com/ParamagicDev/snowpack-plugin-rollup-bundle) + +#### onChange() + +Get notified any time a watched file changes. This can be useful when paired with the `markChanged()` plugin method, to mark multiple files changed at once. + +See [@snowpack/plugin-sass](https://github.com/snowpackjs/snowpack/tree/main/plugins/plugin-sass/plugin.js) for an example of how to use this method. + +### Plugin Properties + +#### knownEntrypoints + +``` +// Example: Svelte plugin needs to make sure this dependency can be loaded. +knownEntrypoints: ["svelte/internal"] +``` + +A list of any npm dependencies that are added as a part of `load()` or `transform()` that Snowpack will need to know about. Snowpack analyzes most dependency imports automatically when it scans the source code of a project, but some imports are added as a part of a `load()` or `transform()` step, which means that Snowpack would never see them. If your plugin does this, add them here. + +#### resolve + +``` +// Example: Sass plugin compiles Sass files to CSS. +resolve: {input: [".sass"], output: [".css"]} + +// Example: Svelte plugin compiles Svelte files to JS & CSS. +resolve: {input: [".svelte"], output: [".js", ".css"]} +``` + +If your plugin defines a `load()` method, Snowpack will need to know what files your plugin is responsible to load and what its output will look like. **`resolve` is needed only if you also define a `load()` method.** + +- `input`: An array of file extensions that this plugin will load. +- `output`: The set of all file extensions that this plugin's `load()` method will output. +- [Full TypeScript definition](https://github.com/snowpackjs/snowpack/tree/main/snowpack/src/types/snowpack.ts). + +### Plugin Methods + +#### this.markChanged() + +```js +// Called inside any plugin hooks +this.markChanged('/some/file/path.scss'); +``` + +Manually mark a file as changed, regardless of whether the file changed on disk or not. This can be useful when paired with the `markChanged()` plugin hook, to mark multiple files changed at once. + +- See [@snowpack/plugin-sass](https://github.com/snowpackjs/snowpack/tree/main/plugins/plugin-sass/plugin.js) for an example of how to use this method. +- [Full TypeScript definition](https://github.com/snowpackjs/snowpack/blob/main/snowpack/src/types.ts). diff --git a/examples/snowpack/src/pages/reference/supported-files.md b/examples/snowpack/src/pages/reference/supported-files.md new file mode 100644 index 000000000..c111247dc --- /dev/null +++ b/examples/snowpack/src/pages/reference/supported-files.md @@ -0,0 +1,119 @@ +--- +layout: ../../layouts/content.astro +title: Supported Files +description: Snowpack ships with built-in support for many file types including json, js, ts, jsx, css, css modules, and images. +--- + +Snowpack ships with built-in support for the following file types, no configuration required: + +- JavaScript (`.js`, `.mjs`) +- TypeScript (`.ts`, `.tsx`) +- JSON (`.json`) +- JSX (`.jsx`, `.tsx`) +- CSS (`.css`) +- CSS Modules (`.module.css`) +- Images & Assets (`.svg`, `.jpg`, `.png`, etc.) +- WASM (`.wasm`) + +To customize build behavior and support new languages [check out our tooling guide](/guides/connecting-tools) + +### JavaScript & ESM + +Snowpack was designed to support JavaScript's native ES Module (ESM) syntax. ESM lets you define explicit imports & exports that browsers and build tools can better understand and optimize for. If you're familiar with the `import` and `export` keywords in JavaScript, then you already know ESM! + +```js +// ESM Example - src/user.js +export function getUser() { + /* ... */ +} + +// src/index.js +import { getUser } from './user.js'; +``` + +All modern browsers support ESM, so Snowpack is able to ship this code directly to the browser during development. This is what makes Snowpack's **unbundled development** workflow possible. + +Snowpack also lets you import non-JavaScript files directly in your application. Snowpack handles all this for you automatically so there's nothing to configure, using the following logic: + +### TypeScript + +Snowpack includes built-in support to build TypeScript files (`*.ts`) to JavaScript. + +Note that this built-in support is build only. By default, Snowpack does not type-check your TypeScript code. To integrate type checking into your development/build workflow, add the [@snowpack/plugin-typescript](https://www.npmjs.com/package/@snowpack/plugin-typescript) plugin. + +### JSX + +Snowpack includes built-in support to build JSX files (`*.jsx` & `*.tsx`) to JavaScript. + +If you are using Preact, Snowpack will detect this and switch to use the Preact-style JSX `h()` function. This is all done automatically for you. If you need to customize this behavior, consider adding the [@snowpack/plugin-babel](https://www.npmjs.com/package/@snowpack/plugin-babel) plugin for full compiler customization via Babel. + +**Note: Snowpack's default build does not support JSX in `.js`/`.ts` files.** If you can't use the `.jsx`/`.tsx` file extension, you can use [@snowpack/plugin-babel](https://www.npmjs.com/package/@snowpack/plugin-babel) to build your JavaScript instead. + +### JSON + +```js +// Load the JSON object via the default export +import json from './data.json'; +``` + +Snowpack supports importing JSON files directly into your application. Imported files return the full JSON object in the default import. + +### CSS + +```js +// Load and inject 'style.css' onto the page +import './style.css'; +``` + +Snowpack supports importing CSS files directly into your application. Imported styles expose no exports, but importing one will automatically add those styles to the page. This works for all CSS files by default, and can support compile-to-CSS languages like Sass & Less via plugins. + +If you prefer not to write CSS, Snowpack also supports all popular CSS-in-JS libraries (ex: styled-components) for styling. + +### CSS Modules + +```js +// 1. Converts './style.module.css' classnames to unique, scoped values. +// 2. Returns an object mapping the original classnames to their final, scoped value. +import styles from './style.module.css'; + +// This example uses JSX, but you can use CSS Modules with any framework. +return <div className={styles.error}>Your Error Message</div>; +``` + +Snowpack supports CSS Modules using the `[name].module.css` naming convention. Like any CSS file, importing one will automatically apply that CSS to the page. However, CSS Modules export a special default `styles` object that maps your original classnames to unique identifiers. + +CSS Modules help you enforce component scoping & isolation on the frontend with unique-generated class names for your stylesheets. + +### Other Assets + +```jsx +import imgReference from './image.png'; // img === '/src/image.png' +import svgReference from './image.svg'; // svg === '/src/image.svg' +import txtReference from './words.txt'; // txt === '/src/words.txt' + +// This example uses JSX, but you can use import references with any framework. +<img src={imgReference} />; +``` + +All other assets not explicitly mentioned above can be imported via ESM `import` and will return a URL reference to the final built asset. This can be useful for referencing non-JS assets by URL, like creating an image element with a `src` attribute pointing to that image. + +### WASM + +```js +// Loads and intializes the requested WASM file +const wasm = await WebAssembly.instantiateStreaming(fetch('/example.wasm')); +``` + +Snowpack supports loading WASM files directly into your application using the browser's [`WebAssembly`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly) API. Read our [WASM guide](/guides/wasm) to learn more. + +### Import NPM Packages + +```js +// Returns the React & React-DOM npm packages +import React from 'react'; +import ReactDOM from 'react-dom'; +``` + +Snowpack lets you import npm packages directly in the browser. Even if a package was published using a legacy format, Snowpack will up-convert the package to ESM before serving it to the browser. + +When you start up your dev server or run a new build, you may see a message that Snowpack is "installing dependencies". This means that Snowpack is converting your dependencies to run in the browser. This needs to run only once, or until you next change your dependency tree by adding or removing dependencies. |