@sveltejs/vite-plugin-svelte
Advanced tools
Comparing version 1.0.0-next.10 to 1.0.0-next.11
# @sveltejs/vite-plugin-svelte | ||
## 1.0.0-next.11 | ||
### Major Changes | ||
- [#54](https://github.com/sveltejs/vite-plugin-svelte/pull/54) [`0f7e256`](https://github.com/sveltejs/vite-plugin-svelte/commit/0f7e256a9ebb0ee9ac6075146d27bf4f11ecdab3) feat: convert to es module with cjs fallback, use named export instead of default | ||
If you are using vite-plugin-svelte with require, you should switch to esm and import the named export "svelte". | ||
An example can be found in the usage section of the [readme](README.md) | ||
For existing esm configs update your import to use the new named export. | ||
```diff | ||
- import svelte from '@sveltejs/vite-plugin-svelte'; | ||
+ import { svelte } from '@sveltejs/vite-plugin-svelte'; | ||
``` | ||
continuing with cjs/require is discouraged but if you must use it, update your require statement to use the named export | ||
```diff | ||
- const svelte = require('@sveltejs/vite-plugin-svelte'); | ||
+ const { svelte } = require('@sveltejs/vite-plugin-svelte'); | ||
``` | ||
### Minor Changes | ||
- [#45](https://github.com/sveltejs/vite-plugin-svelte/pull/45) [`673cf61`](https://github.com/sveltejs/vite-plugin-svelte/commit/673cf61b3800e7a64be2b73a7273909da95729d2) Feature: log svelte compiler warnings to console. use options.onwarn to customize logging | ||
### Patch Changes | ||
- [#44](https://github.com/sveltejs/vite-plugin-svelte/pull/44) [`24ae093`](https://github.com/sveltejs/vite-plugin-svelte/commit/24ae0934301cb50506bf39cdccc07ad3eac546fd) update to esbuild 0.12 and vite 2.3.7 | ||
* [#44](https://github.com/sveltejs/vite-plugin-svelte/pull/44) [`24ae093`](https://github.com/sveltejs/vite-plugin-svelte/commit/24ae0934301cb50506bf39cdccc07ad3eac546fd) update engines.node to "^12.20 || ^14.13.1 || >= 16" | ||
- [#45](https://github.com/sveltejs/vite-plugin-svelte/pull/45) [`673cf61`](https://github.com/sveltejs/vite-plugin-svelte/commit/673cf61b3800e7a64be2b73a7273909da95729d2) enable logging for compiler warnings | ||
## 1.0.0-next.10 | ||
@@ -4,0 +39,0 @@ |
@@ -1,44 +0,4 @@ | ||
import { Plugin as Plugin_2 } from 'vite'; | ||
import { Plugin } from 'vite'; | ||
export declare type Arrayable<T> = T | T[]; | ||
export declare interface CompileOptions { | ||
format?: ModuleFormat; | ||
name?: string; | ||
filename?: string; | ||
generate?: 'dom' | 'ssr' | false; | ||
sourcemap?: object | string; | ||
outputFilename?: string; | ||
cssOutputFilename?: string; | ||
sveltePath?: string; | ||
dev?: boolean; | ||
accessors?: boolean; | ||
immutable?: boolean; | ||
hydratable?: boolean; | ||
legacy?: boolean; | ||
customElement?: boolean; | ||
tag?: string; | ||
css?: boolean; | ||
loopGuardTimeout?: number; | ||
namespace?: string; | ||
preserveComments?: boolean; | ||
preserveWhitespace?: boolean; | ||
cssHash?: CssHashGetter; | ||
} | ||
export declare type CssHashGetter = (args: { | ||
name: string; | ||
filename: string | undefined; | ||
css: string; | ||
hash: (input: string) => string; | ||
}) => string; | ||
export declare type MarkupPreprocessor = (options: { | ||
content: string; | ||
filename: string; | ||
}) => Processed | Promise<Processed>; | ||
export declare type ModuleFormat = 'esm' | 'cjs'; | ||
export declare interface Options { | ||
interface Options { | ||
/** path to svelte config file, either absolute or relative to vite root*/ | ||
@@ -66,4 +26,7 @@ configFile?: string; | ||
compilerOptions: Partial<CompileOptions>; | ||
onwarn?: undefined | false | ((warning: any, defaultHandler?: any) => void); | ||
/** | ||
* custom warning handler for svelte compiler warnings | ||
*/ | ||
onwarn?: (warning: Warning, defaultHandler?: (warning: Warning) => void) => void; | ||
/** | ||
* enable/disable hmr. You want this enabled. | ||
@@ -192,10 +155,48 @@ * | ||
} | ||
export declare type Preprocessor = (options: { | ||
declare type ModuleFormat = 'esm' | 'cjs'; | ||
interface CompileOptions { | ||
format?: ModuleFormat; | ||
name?: string; | ||
filename?: string; | ||
generate?: 'dom' | 'ssr' | false; | ||
sourcemap?: object | string; | ||
outputFilename?: string; | ||
cssOutputFilename?: string; | ||
sveltePath?: string; | ||
dev?: boolean; | ||
accessors?: boolean; | ||
immutable?: boolean; | ||
hydratable?: boolean; | ||
legacy?: boolean; | ||
customElement?: boolean; | ||
tag?: string; | ||
css?: boolean; | ||
loopGuardTimeout?: number; | ||
namespace?: string; | ||
preserveComments?: boolean; | ||
preserveWhitespace?: boolean; | ||
cssHash?: CssHashGetter; | ||
} | ||
interface Processed { | ||
code: string; | ||
map?: string | object; | ||
dependencies?: string[]; | ||
toString?: () => string; | ||
} | ||
declare type CssHashGetter = (args: { | ||
name: string; | ||
filename: string | undefined; | ||
css: string; | ||
hash: (input: string) => string; | ||
}) => string; | ||
declare type MarkupPreprocessor = (options: { | ||
content: string; | ||
filename: string; | ||
}) => Processed | Promise<Processed>; | ||
declare type Preprocessor = (options: { | ||
content: string; | ||
attributes: Record<string, string | boolean>; | ||
filename?: string; | ||
}) => Processed | Promise<Processed>; | ||
export declare interface PreprocessorGroup { | ||
interface PreprocessorGroup { | ||
markup?: MarkupPreprocessor; | ||
@@ -205,13 +206,28 @@ style?: Preprocessor; | ||
} | ||
export declare interface Processed { | ||
declare type Arrayable<T> = T | T[]; | ||
interface Warning { | ||
start?: { | ||
line: number; | ||
column: number; | ||
pos?: number; | ||
}; | ||
end?: { | ||
line: number; | ||
column: number; | ||
}; | ||
pos?: number; | ||
code: string; | ||
map?: string | object; | ||
dependencies?: string[]; | ||
toString?: () => string; | ||
message: string; | ||
filename?: string; | ||
frame?: string; | ||
toString: () => string; | ||
} | ||
declare function vitePluginSvelte(inlineOptions?: Partial<Options>): Plugin_2; | ||
export default vitePluginSvelte; | ||
declare module 'vite' { | ||
interface Plugin { | ||
sveltePreprocess?: PreprocessorGroup; | ||
} | ||
} | ||
declare function svelte(inlineOptions?: Partial<Options>): Plugin; | ||
export { } | ||
export { Arrayable, CompileOptions, CssHashGetter, MarkupPreprocessor, ModuleFormat, Options, Preprocessor, PreprocessorGroup, Processed, Warning, svelte }; |
@@ -1,11 +0,9 @@ | ||
var __create = Object.create; | ||
var __defProp = Object.defineProperty; | ||
var __getProtoOf = Object.getPrototypeOf; | ||
var __defProps = Object.defineProperties; | ||
var __getOwnPropDescs = Object.getOwnPropertyDescriptors; | ||
var __getOwnPropSymbols = Object.getOwnPropertySymbols; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __getOwnPropNames = Object.getOwnPropertyNames; | ||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor; | ||
var __getOwnPropSymbols = Object.getOwnPropertySymbols; | ||
var __propIsEnum = Object.prototype.propertyIsEnumerable; | ||
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value; | ||
var __assign = (a, b) => { | ||
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; | ||
var __spreadValues = (a, b) => { | ||
for (var prop in b || (b = {})) | ||
@@ -21,30 +19,12 @@ if (__hasOwnProp.call(b, prop)) | ||
}; | ||
var __markAsModule = (target) => __defProp(target, "__esModule", {value: true}); | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, {get: all[name], enumerable: true}); | ||
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); | ||
var __require = (x) => { | ||
if (typeof require !== "undefined") | ||
return require(x); | ||
throw new Error('Dynamic require of "' + x + '" is not supported'); | ||
}; | ||
var __exportStar = (target, module2, desc) => { | ||
if (module2 && typeof module2 === "object" || typeof module2 === "function") { | ||
for (let key of __getOwnPropNames(module2)) | ||
if (!__hasOwnProp.call(target, key) && key !== "default") | ||
__defProp(target, key, {get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable}); | ||
} | ||
return target; | ||
}; | ||
var __toModule = (module2) => { | ||
return __exportStar(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? {get: () => module2.default, enumerable: true} : {value: module2, enumerable: true})), module2); | ||
}; | ||
// src/index.ts | ||
__markAsModule(exports); | ||
__export(exports, { | ||
default: () => vitePluginSvelte | ||
}); | ||
var path2 = __toModule(require("path")); | ||
var relative = __toModule(require("require-relative")); | ||
// src/utils/log.ts | ||
var import_chalk = __toModule(require("chalk")); | ||
var import_debug = __toModule(require("debug")); | ||
import chalk from "chalk"; | ||
import debug from "debug"; | ||
var levels = ["debug", "info", "warn", "error", "silent"]; | ||
@@ -54,3 +34,3 @@ var prefix = "vite-plugin-svelte"; | ||
debug: { | ||
log: (0, import_debug.default)(`vite:${prefix}`), | ||
log: debug(`vite:${prefix}`), | ||
enabled: false, | ||
@@ -60,3 +40,3 @@ isDebug: true | ||
info: { | ||
color: import_chalk.default.cyan, | ||
color: chalk.cyan, | ||
log: console.log, | ||
@@ -66,3 +46,3 @@ enabled: true | ||
warn: { | ||
color: import_chalk.default.yellow, | ||
color: chalk.yellow, | ||
log: console.warn, | ||
@@ -72,3 +52,3 @@ enabled: true | ||
error: { | ||
color: import_chalk.default.red, | ||
color: chalk.red, | ||
log: console.error, | ||
@@ -134,6 +114,39 @@ enabled: true | ||
}; | ||
function logCompilerWarnings(warnings, options) { | ||
const { emitCss, onwarn, isBuild } = options; | ||
const warn = isBuild ? warnBuild : warnDev; | ||
warnings == null ? void 0 : warnings.forEach((warning) => { | ||
if (!emitCss && warning.code === "css-unused-selector") { | ||
return; | ||
} | ||
if (onwarn) { | ||
onwarn(warning, warn); | ||
} else { | ||
warn(warning); | ||
} | ||
}); | ||
} | ||
function warnDev(w) { | ||
log.info.enabled && log.info(buildExtendedLogMessage(w)); | ||
} | ||
function warnBuild(w) { | ||
log.warn.enabled && log.warn(buildExtendedLogMessage(w), w.frame); | ||
} | ||
function buildExtendedLogMessage(w) { | ||
const parts = []; | ||
if (w.filename) { | ||
parts.push(w.filename); | ||
} | ||
if (w.start) { | ||
parts.push(":", w.start.line, ":", w.start.column); | ||
} | ||
if (w.message) { | ||
parts.push(" ", w.message); | ||
} | ||
return parts.join(""); | ||
} | ||
// src/handleHotUpdate.ts | ||
// src/handle-hot-update.ts | ||
async function handleHotUpdate(compileSvelte, ctx, svelteRequest, cache, options) { | ||
const {read, server} = ctx; | ||
const { read, server } = ctx; | ||
const cachedJS = cache.getJS(svelteRequest); | ||
@@ -151,10 +164,15 @@ if (!cachedJS) { | ||
const mainModule = server.moduleGraph.getModuleById(svelteRequest.id); | ||
if (cssModule && cssChanged(cachedCss, compileData.compiled.css)) { | ||
const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css); | ||
if (cssUpdated) { | ||
log.debug("handleHotUpdate css changed"); | ||
affectedModules.add(cssModule); | ||
} | ||
if (mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename)) { | ||
const jsUpdated = mainModule && jsChanged(cachedJS, compileData.compiled.js, svelteRequest.filename); | ||
if (jsUpdated) { | ||
log.debug("handleHotUpdate js changed"); | ||
affectedModules.add(mainModule); | ||
} | ||
if (!jsUpdated) { | ||
logCompilerWarnings(compileData.compiled.warnings, options); | ||
} | ||
const result = [...affectedModules].filter(Boolean); | ||
@@ -202,7 +220,9 @@ log.debug(`handleHotUpdate result for ${svelteRequest.id}`, result); | ||
// src/utils/compile.ts | ||
var import_compiler = __toModule(require("svelte/compiler")); | ||
var import_svelte_hmr = __toModule(require("svelte-hmr")); | ||
import { compile, preprocess, walk } from "svelte/compiler"; | ||
import { createMakeHot } from "svelte-hmr"; | ||
// src/utils/hash.ts | ||
var crypto = __toModule(require("crypto")); | ||
import { | ||
createHash | ||
} from "crypto"; | ||
var hashes = Object.create(null); | ||
@@ -214,3 +234,3 @@ var hash_length = 12; | ||
} | ||
const md5 = crypto.createHash("md5"); | ||
const md5 = createHash("md5"); | ||
md5.update(input); | ||
@@ -233,6 +253,6 @@ const hash = toSafe(md5.digest("base64")).substr(0, hash_length); | ||
var _createCompileSvelte = (makeHot) => async function compileSvelte(svelteRequest, code, options) { | ||
const {filename, normalizedFilename, cssId, ssr} = svelteRequest; | ||
const {onwarn, emitCss = true} = options; | ||
const { filename, normalizedFilename, cssId, ssr } = svelteRequest; | ||
const { emitCss = true } = options; | ||
const dependencies = []; | ||
const finalCompilerOptions = __assign(__assign({}, options.compilerOptions), { | ||
const finalCompilerOptions = __spreadProps(__spreadValues({}, options.compilerOptions), { | ||
filename, | ||
@@ -248,3 +268,3 @@ generate: ssr ? "ssr" : "dom" | ||
if (options.preprocess) { | ||
preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, {filename}); | ||
preprocessed = await preprocess(code, options.preprocess, { filename }); | ||
if (preprocessed.dependencies) | ||
@@ -255,9 +275,3 @@ dependencies.push(...preprocessed.dependencies); | ||
} | ||
const compiled = (0, import_compiler.compile)(preprocessed ? preprocessed.code : code, finalCompilerOptions); | ||
(compiled.warnings || []).forEach((warning) => { | ||
if (!emitCss && warning.code === "css-unused-selector") | ||
return; | ||
if (onwarn) | ||
onwarn(warning); | ||
}); | ||
const compiled = compile(preprocessed ? preprocessed.code : code, finalCompilerOptions); | ||
if (emitCss && compiled.css.code) { | ||
@@ -293,7 +307,7 @@ compiled.js.code += ` | ||
const adapter = (_b = options == null ? void 0 : options.hot) == null ? void 0 : _b.adapter; | ||
return (0, import_svelte_hmr.createMakeHot)({ | ||
walk: import_compiler.walk, | ||
return createMakeHot({ | ||
walk, | ||
hotApi, | ||
adapter, | ||
hotOptions: __assign({noOverlay: true}, options.hot) | ||
hotOptions: __spreadValues({ noOverlay: true }, options.hot) | ||
}); | ||
@@ -308,6 +322,8 @@ } | ||
// src/utils/id.ts | ||
var import_querystring = __toModule(require("querystring")); | ||
var import_pluginutils = __toModule(require("@rollup/pluginutils")); | ||
var import_vite = __toModule(require("vite")); | ||
var fs = __toModule(require("fs")); | ||
import qs from "querystring"; | ||
import { createFilter } from "@rollup/pluginutils"; | ||
import { normalizePath } from "vite"; | ||
import { | ||
existsSync | ||
} from "fs"; | ||
var VITE_FS_PREFIX = "/@fs/"; | ||
@@ -319,6 +335,6 @@ var IS_WINDOWS = process.platform === "win32"; | ||
const rawQuery = parts[1]; | ||
return {filename, rawQuery}; | ||
return { filename, rawQuery }; | ||
} | ||
function parseToSvelteRequest(id, filename, rawQuery, root, timestamp, ssr) { | ||
const query = import_querystring.default.parse(rawQuery); | ||
const query = qs.parse(rawQuery); | ||
if (query.svelte != null) { | ||
@@ -352,3 +368,3 @@ query.svelte = true; | ||
function normalize(filename, normalizedRoot) { | ||
return stripRoot((0, import_vite.normalizePath)(filename), normalizedRoot); | ||
return stripRoot(normalizePath(filename), normalizedRoot); | ||
} | ||
@@ -359,3 +375,3 @@ function existsInRoot(filename, root) { | ||
} | ||
return fs.existsSync(root + filename); | ||
return existsSync(root + filename); | ||
} | ||
@@ -366,11 +382,11 @@ function stripRoot(normalizedFilename, normalizedRoot) { | ||
function buildFilter(include, exclude, extensions) { | ||
const rollupFilter = (0, import_pluginutils.createFilter)(include, exclude); | ||
const rollupFilter = createFilter(include, exclude); | ||
return (filename) => rollupFilter(filename) && extensions.some((ext) => filename.endsWith(ext)); | ||
} | ||
function buildIdParser(options) { | ||
const {include, exclude, extensions, root} = options; | ||
const normalizedRoot = (0, import_vite.normalizePath)(root); | ||
const { include, exclude, extensions, root } = options; | ||
const normalizedRoot = normalizePath(root); | ||
const filter = buildFilter(include, exclude, extensions); | ||
return (id, ssr, timestamp = Date.now()) => { | ||
const {filename, rawQuery} = splitId(id); | ||
const { filename, rawQuery } = splitId(id); | ||
if (filter(filename)) { | ||
@@ -382,6 +398,6 @@ return parseToSvelteRequest(id, filename, rawQuery, normalizedRoot, timestamp, ssr); | ||
// src/utils/loadSvelteConfig.ts | ||
var import_path = __toModule(require("path")); | ||
var import_fs = __toModule(require("fs")); | ||
var import_url = __toModule(require("url")); | ||
// src/utils/load-svelte-config.ts | ||
import path from "path"; | ||
import fs2 from "fs"; | ||
import { pathToFileURL } from "url"; | ||
var knownSvelteConfigNames = ["svelte.config.js", "svelte.config.cjs", "svelte.config.mjs"]; | ||
@@ -395,5 +411,5 @@ var dynamicImportDefault = new Function("path", "return import(path).then(m => m.default)"); | ||
try { | ||
return await dynamicImportDefault((0, import_url.pathToFileURL)(configFile).href); | ||
return await dynamicImportDefault(pathToFileURL(configFile).href); | ||
} catch (e) { | ||
log.debug(`failed to import config ${configFile}`, e); | ||
log.error(`failed to import config ${configFile}`, e); | ||
err = e; | ||
@@ -403,3 +419,3 @@ } | ||
try { | ||
return require(configFile); | ||
return __require(configFile); | ||
} catch (e) { | ||
@@ -417,4 +433,4 @@ log.error(`failed to require config ${configFile}`, e); | ||
if (inlineOptions.configFile) { | ||
const abolutePath = import_path.default.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : import_path.default.resolve(root, inlineOptions.configFile); | ||
if (!import_fs.default.existsSync(abolutePath)) { | ||
const abolutePath = path.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : path.resolve(root, inlineOptions.configFile); | ||
if (!fs2.existsSync(abolutePath)) { | ||
throw new Error(`failed to find svelte config file ${abolutePath}.`); | ||
@@ -424,3 +440,3 @@ } | ||
} else { | ||
const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => import_path.default.resolve(root, candidate)).filter((file) => import_fs.default.existsSync(file)); | ||
const existingKnownConfigFiles = knownSvelteConfigNames.map((candidate) => path.resolve(root, candidate)).filter((file) => fs2.existsSync(file)); | ||
if (existingKnownConfigFiles.length === 0) { | ||
@@ -448,7 +464,7 @@ log.debug(`no svelte config found at ${root}`); | ||
const pluginTransform = plugin.transform.bind(null); | ||
return async ({attributes, content, filename}) => { | ||
return async ({ attributes, content, filename }) => { | ||
var _a, _b, _c, _d; | ||
const lang = attributes.lang; | ||
if (!supportedLangs.includes(lang)) { | ||
return {code: content}; | ||
return { code: content }; | ||
} | ||
@@ -480,3 +496,3 @@ const moduleId = `${filename}.${lang}`; | ||
return { | ||
style({content}) { | ||
style({ content }) { | ||
return { | ||
@@ -525,2 +541,3 @@ code: `${content} *{}` | ||
"compilerOptions", | ||
"onwarn", | ||
"preprocess", | ||
@@ -531,3 +548,3 @@ "hot", | ||
]); | ||
function buildDefaultOptions({isProduction}, options) { | ||
function buildDefaultOptions({ isProduction }, options) { | ||
const disableCssHmr = !!(options == null ? void 0 : options.disableCssHmr); | ||
@@ -577,3 +594,3 @@ const emitCss = (options == null ? void 0 : options.emitCss) != null ? options.emitCss : isProduction || !disableCssHmr; | ||
if (options.hot === true) { | ||
options.hot = {injectCss: true}; | ||
options.hot = { injectCss: true }; | ||
} else { | ||
@@ -603,4 +620,4 @@ options.hot.injectCss = true; | ||
function mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig) { | ||
return __assign(__assign(__assign(__assign({}, defaultOptions), svelteConfig), inlineOptions), { | ||
compilerOptions: __assign(__assign(__assign({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}), | ||
return __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), { | ||
compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}), | ||
root: viteConfig.root, | ||
@@ -623,3 +640,3 @@ isProduction: viteConfig.isProduction, | ||
// src/utils/VitePluginSvelteCache.ts | ||
// src/utils/vite-plugin-svelte-cache.ts | ||
var VitePluginSvelteCache = class { | ||
@@ -715,3 +732,3 @@ constructor() { | ||
// src/utils/watch.ts | ||
var import_fs2 = __toModule(require("fs")); | ||
import fs3 from "fs"; | ||
function setupWatchers(server, cache, requestParser) { | ||
@@ -722,3 +739,3 @@ const watcher = server.watcher; | ||
dependants.forEach((dependant) => { | ||
if (import_fs2.default.existsSync(dependant)) { | ||
if (fs3.existsSync(dependant)) { | ||
log.debug(`emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`); | ||
@@ -745,5 +762,32 @@ watcher.emit("change", dependant); | ||
// src/utils/resolve.ts | ||
import path2 from "path"; | ||
import fs4 from "fs"; | ||
import relative from "require-relative"; | ||
function resolveViaPackageJsonSvelte(importee, importer) { | ||
if (importer && isBareImport(importee)) { | ||
const importeePkgFile = relative.resolve(`${importee}/package.json`, path2.dirname(importer)); | ||
const importeePkg = JSON.parse(fs4.readFileSync(importeePkgFile, { encoding: "utf-8" })); | ||
if (importeePkg.svelte) { | ||
return path2.resolve(path2.dirname(importeePkgFile), importeePkg.svelte); | ||
} | ||
} | ||
} | ||
function isBareImport(importee) { | ||
if (!importee || importee[0] === "." || importee[0] === "\0" || path2.isAbsolute(importee)) { | ||
return false; | ||
} | ||
const parts = importee.split("/"); | ||
switch (parts.length) { | ||
case 1: | ||
return true; | ||
case 2: | ||
return parts[0].startsWith("@"); | ||
default: | ||
return false; | ||
} | ||
} | ||
// src/index.ts | ||
var pkg_export_errors = new Set(); | ||
function vitePluginSvelte(inlineOptions) { | ||
function svelte(inlineOptions) { | ||
if (process.env.DEBUG != null) { | ||
@@ -754,2 +798,3 @@ log.setLevel("debug"); | ||
const cache = new VitePluginSvelteCache(); | ||
const pkg_export_errors = new Set(); | ||
let requestParser; | ||
@@ -803,3 +848,3 @@ let options; | ||
log.debug("load", svelteRequest); | ||
const {filename, query} = svelteRequest; | ||
const { filename, query } = svelteRequest; | ||
if (query.svelte) { | ||
@@ -826,28 +871,19 @@ if (query.type === "style") { | ||
} | ||
if (!importer || importee[0] === "." || importee[0] === "\0" || path2.isAbsolute(importee)) { | ||
return null; | ||
} | ||
const parts = importee.split("/"); | ||
let dir, pkg, name = parts.shift(); | ||
if (name && name[0] === "@") { | ||
name += `/${parts.shift()}`; | ||
} | ||
try { | ||
const file = `${name}/package.json`; | ||
const resolved = relative.resolve(file, path2.dirname(importer)); | ||
dir = path2.dirname(resolved); | ||
pkg = require(resolved); | ||
const resolved = resolveViaPackageJsonSvelte(importee, importer); | ||
if (resolved) { | ||
log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`); | ||
return resolved; | ||
} | ||
} catch (err) { | ||
if (err.code === "MODULE_NOT_FOUND") | ||
return null; | ||
if (err.code === "ERR_PACKAGE_PATH_NOT_EXPORTED") { | ||
pkg_export_errors.add(name); | ||
return null; | ||
switch (err.code) { | ||
case "ERR_PACKAGE_PATH_NOT_EXPORTED": | ||
pkg_export_errors.add(importee); | ||
return null; | ||
case "MODULE_NOT_FOUND": | ||
return null; | ||
default: | ||
throw err; | ||
} | ||
throw err; | ||
} | ||
if (parts.length === 0 && pkg.svelte) { | ||
return path2.resolve(dir, pkg.svelte); | ||
} | ||
log.debug(`resolveId did not resolve ${importee}`); | ||
}, | ||
@@ -861,3 +897,3 @@ async transform(code, id, ssr) { | ||
log.debug("transform", svelteRequest); | ||
const {filename, query} = svelteRequest; | ||
const { filename, query } = svelteRequest; | ||
if (query.svelte) { | ||
@@ -875,2 +911,3 @@ if (query.type === "style") { | ||
const compileData = await compileSvelte(svelteRequest, code, options); | ||
logCompilerWarnings(compileData.compiled.warnings, options); | ||
cache.update(compileData); | ||
@@ -904,5 +941,5 @@ if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) { | ||
} | ||
module.exports = vitePluginSvelte; | ||
vitePluginSvelte["default"] = vitePluginSvelte; | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && (module.exports = {}); | ||
export { | ||
svelte | ||
}; | ||
//# sourceMappingURL=index.js.map |
122
package.json
{ | ||
"name": "@sveltejs/vite-plugin-svelte", | ||
"version": "1.0.0-next.10", | ||
"license": "MIT", | ||
"author": "dominikg", | ||
"files": [ | ||
"dist" | ||
], | ||
"main": "dist/index.js", | ||
"types": "dist/index.d.ts", | ||
"scripts": { | ||
"dev": "tsc -p . -w --incremental", | ||
"build": "rimraf dist && run-s build-bundle build-types", | ||
"build-bundle": "node scripts/build-bundle.js", | ||
"build-types": "tsc -p . --emitDeclarationOnly --outDir temp && api-extractor run && rimraf temp" | ||
}, | ||
"engines": { | ||
"node": ">=12.0.0" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/sveltejs/vite-plugin-svelte.git" | ||
}, | ||
"keywords": [ | ||
"vite-plugin", | ||
"vite plugin", | ||
"vite", | ||
"svelte" | ||
], | ||
"bugs": { | ||
"url": "https://github.com/sveltejs/vite-plugin-svelte/issues" | ||
}, | ||
"homepage": "https://github.com/sveltejs/vite-plugin-svelte/tree/main/packages/vite-plugin-svelte#readme", | ||
"dependencies": { | ||
"@rollup/pluginutils": "^4.1.0", | ||
"chalk": "^4.1.1", | ||
"debug": "^4.3.2", | ||
"hash-sum": "^2.0.0", | ||
"require-relative": "^0.8.7", | ||
"slash": "^4.0.0", | ||
"source-map": "^0.7.3", | ||
"svelte-hmr": "^0.14.2" | ||
}, | ||
"peerDependencies": { | ||
"svelte": "^3.37.0", | ||
"vite": "^2.2.3" | ||
}, | ||
"devDependencies": { | ||
"@types/debug": "^4.1.5", | ||
"@types/es-module-lexer": "^0.3.0", | ||
"@types/estree": "^0.0.47", | ||
"@types/hash-sum": "^1.0.0", | ||
"@windicss/plugin-utils": "^0.15.7", | ||
"esbuild": "~0.9.7", | ||
"locate-character": "^2.0.5", | ||
"magic-string": "^0.25.7", | ||
"rollup": "^2.45.2", | ||
"svelte": "^3.37.0", | ||
"vite": "^2.2.3" | ||
} | ||
"name": "@sveltejs/vite-plugin-svelte", | ||
"version": "1.0.0-next.11", | ||
"license": "MIT", | ||
"author": "dominikg", | ||
"files": [ | ||
"dist", | ||
"src", | ||
"README.md", | ||
"LICENSE", | ||
"package.json" | ||
], | ||
"type": "module", | ||
"main": "dist/index.cjs", | ||
"module": "dist/index.js", | ||
"types": "dist/index.d.ts", | ||
"exports": { | ||
".": { | ||
"import": "./dist/index.js", | ||
"require": "./dist/index.cjs" | ||
}, | ||
"./package.json": "./package.json" | ||
}, | ||
"scripts": { | ||
"dev": "pnpm run build:ci -- --watch src", | ||
"build:ci": "rimraf dist && tsup-node src/index.ts --format esm,cjs --no-splitting", | ||
"build": "pnpm run build:ci -- --dts --dts-resolve --sourcemap" | ||
}, | ||
"engines": { | ||
"node": "^12.20 || ^14.13.1 || >= 16" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/sveltejs/vite-plugin-svelte.git" | ||
}, | ||
"keywords": [ | ||
"vite-plugin", | ||
"vite plugin", | ||
"vite", | ||
"svelte" | ||
], | ||
"bugs": { | ||
"url": "https://github.com/sveltejs/vite-plugin-svelte/issues" | ||
}, | ||
"homepage": "https://github.com/sveltejs/vite-plugin-svelte/tree/main/packages/vite-plugin-svelte#readme", | ||
"dependencies": { | ||
"@rollup/pluginutils": "^4.1.0", | ||
"chalk": "^4.1.1", | ||
"debug": "^4.3.2", | ||
"require-relative": "^0.8.7", | ||
"svelte-hmr": "^0.14.4" | ||
}, | ||
"peerDependencies": { | ||
"svelte": "^3.38.2", | ||
"vite": "^2.3.7" | ||
}, | ||
"devDependencies": { | ||
"@types/debug": "^4.1.5", | ||
"esbuild": "^0.12.8", | ||
"rollup": "^2.51.1", | ||
"svelte": "^3.38.2", | ||
"tsup": "^4.11.2", | ||
"vite": "^2.3.7" | ||
} | ||
} |
@@ -6,7 +6,6 @@ # @sveltejs/vite-plugin-svelte | ||
```js | ||
// vite.config.js | ||
const svelte = require('@sveltejs/vite-plugin-svelte'); | ||
const { defineConfig } = require('vite'); | ||
import { svelte } from '@sveltejs/vite-plugin-svelte'; | ||
import { defineConfig } from 'vite'; | ||
module.exports = defineConfig(({ command, mode }) => { | ||
export default defineConfig(({ command, mode }) => { | ||
const isProduction = mode === 'production'; | ||
@@ -26,2 +25,12 @@ return { | ||
### commonjs | ||
If you cannot use import and need commonjs, vite-plugin-svelte provides a fallback build in `dist/index.cjs` | ||
require it like this: | ||
```js | ||
const { svelte } = require('@sveltejs/vite-plugin-svelte'); | ||
``` | ||
## Options | ||
@@ -33,3 +42,3 @@ | ||
Options are applied in the following order: | ||
Options are merged in the following order: | ||
@@ -44,2 +53,22 @@ 1. vite-plugin-svelte defaults | ||
## Importing third-party Svelte libraries | ||
When importing any third-party libraries that uses Svelte's lifecycle API, e.g. `onMount`, `setContext`, and others, they need to be excluded from Vite's dependency pre-bundling process: | ||
<!-- eslint-skip --> | ||
```js | ||
// vite.config.js | ||
{ | ||
plugins: [svelte()], | ||
optimizeDeps: { | ||
exclude: ['svelte-library'] | ||
} | ||
} | ||
``` | ||
This is needed because Vite's dependency pre-bundling doesn't deduplicate the Svelte instance, resulting in multiple Svelte instance running at once, causing errors like `Function called outside component initialization`. | ||
If you're unsure whether a library uses the lifecycle API, place it in `optimizeDeps.exclude` and you'll be fine. The team is working on removing this limitation soon. | ||
## Integrations for other vite plugins | ||
@@ -46,0 +75,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
245347
7
6
22
3389
92
Yes
14
3
- Removedhash-sum@^2.0.0
- Removedslash@^4.0.0
- Removedsource-map@^0.7.3
- Removedhash-sum@2.0.0(transitive)
- Removedslash@4.0.0(transitive)
- Removedsource-map@0.7.4(transitive)
Updatedsvelte-hmr@^0.14.4