Socket
Socket
Sign inDemoInstall

rollup-plugin-svelte

Package Overview
Dependencies
Maintainers
5
Versions
58
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rollup-plugin-svelte - npm Package Compare versions

Comparing version 6.1.1 to 7.0.0

12

CHANGELOG.md
# rollup-plugin-svelte changelog
## 6.1.1
## Unreleased
* Use `require('svelte/compiler')` rather than `require('svelte/compiler.js')` to work with new Svelte exports map
## 6.1.0
* feat: allow custom Svelte compilers via new `svelte` option: ([#124](https://github.com/sveltejs/rollup-plugin-svelte/pull/124))
* fix: use native `fs.existsSync` method: ([`50e03e5`](https://github.com/sveltejs/rollup-plugin-svelte/commit/50e03e5))
* chore: Power CI via GitHub Action ([`61ead9a..23e83a4`](https://github.com/sveltejs/rollup-plugin-svelte/compare/61ead9a..23e83a4))
## 6.0.2
* Added default value to CssWriter.write map option ([#135](https://github.com/sveltejs/rollup-plugin-svelte/pull/135))

@@ -16,0 +6,0 @@ * Do not warn about missing unused css selectors if both css and emitCss are false ([#127](https://github.com/sveltejs/rollup-plugin-svelte/pull/127))

102

index.d.ts

@@ -1,67 +0,41 @@

import { Plugin, RollupWarning } from 'rollup';
import { Plugin, RollupWarning, SourceMap as Mapping } from 'rollup';
import { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
import { CompileOptions } from 'svelte/types/compiler/interfaces';
interface Css {
code: any;
map: any;
}
type Arrayable<T> = T | T[];
type SourceMap = Omit<Mapping, 'toString' | 'toUrl'>;
type WarningHandler = (warning: RollupWarning | string) => void;
declare class CssWriter {
code: string;
filename: string;
map: {
version: number;
file?: boolean;
sources: string[];
sourcesContent: string[];
names: any[];
mappings: string;
};
warn: RollupWarning;
emit(fileName: string, source: string): void;
write(dest: string, map?: boolean): void;
warn: WarningHandler;
map: false | SourceMap;
write(file: string, map?: boolean): void;
emit(name: string, source: string): string;
sourcemap(file: string, sourcemap: SourceMap): void;
toString(): string;
}
interface Svelte {
compile: any;
preprocess: any;
version: number | string;
}
type CssEmitter = (css: CssWriter) => any;
interface Options {
/**
* By default, all .svelte and .html files are compiled
* @default ['.html', '.svelte']
*/
extensions?: string[];
/** One or more minimatch patterns */
include: Arrayable<string>;
/**
* You can restrict which files are compiled
* using `include` and `exclude`
* @typedef {string} InclureAndExclude
*/
/** One or more minimatch patterns */
exclude: Arrayable<string>;
/**
* @type {IncludeAndExclude}
* By default, all ".svelte" files are compiled
* @default ['.svelte']
*/
include?: string;
/**
* @type {IncludeAndExclude}
*/
exclude?: string;
extensions: string[];
/**
* By default, the client-side compiler is used. You
* can also use the server-side rendering compiler
*/
generate?: 'dom' | 'ssr' | false;
/**
* Optionally, preprocess components with svelte.preprocess:
* https://svelte.dev/docs#svelte_preprocess
* @see https://svelte.dev/docs#svelte_preprocess
*/
preprocess?: PreprocessorGroup | PreprocessorGroup[];
preprocess: Arrayable<PreprocessorGroup>;
// {

@@ -73,34 +47,12 @@ // style: ({ content }) => {

/**
* Emit CSS as "files" for other plugins to process
* @default false
*/
emitCss?: boolean;
/** Emit Svelte styles as virtual CSS files for other plugins to process. */
emitCss: boolean;
/**
* Extract CSS into a separate file (recommended).
*/
css?: false | CssEmitter;
/** Options passed to `svelte.compile` method. */
compilerOptions: CompileOptions;
/**
* Compile Svelte components to custom elements (aka web components).
* @default false
*/
customElement?: boolean;
/**
* Pass in a specific version of Svelte.
*/
svelte?: Svelte;
/**
* let Rollup handle all other warnings normally
*/
onwarn?: (
warning: RollupWarning,
handler: (w: RollupWarning | string) => void
) => void;
/** Custom warnings handler; defers to Rollup as default. */
onwarn(warning: RollupWarning, handler: WarningHandler): void;
}
export default function svelte(options?: Options): Plugin;
export default function svelte(options?: Partial<Options>): Plugin;
const path = require('path');
const { existsSync } = require('fs');
const relative = require('require-relative');
const { createFilter } = require('rollup-pluginutils');
const { encode, decode } = require('sourcemap-codec');
const { compile, preprocess } = require('svelte/compiler');
const PREFIX = '[rollup-plugin-svelte]';
const pkg_export_errors = new Set();
const to_major = str => Number(str[0]);
const plugin_options = new Set([
'include', 'exclude', 'extensions',
'preprocess', 'onwarn', 'emitCss',
]);
function autoload() {
const pkg = require('svelte/package.json');
const version = to_major(pkg.version);
/**
* @param [options] {Partial<import('.').Options>}
* @returns {import('rollup').Plugin}
*/
module.exports = function (options = {}) {
const { compilerOptions={}, ...rest } = options;
const extensions = rest.extensions || ['.svelte'];
const filter = createFilter(rest.include, rest.exclude);
const { compile, preprocess } = require(version >= 3 ? 'svelte/compiler' : 'svelte');
return { compile, preprocess, version };
}
compilerOptions.format = 'esm';
function sanitize(input) {
return path
.basename(input)
.replace(path.extname(input), '')
.replace(/[^a-zA-Z_$0-9]+/g, '_')
.replace(/^_/, '')
.replace(/_$/, '')
.replace(/^(\d)/, '_$1');
}
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
const pluginOptions = {
include: true,
exclude: true,
extensions: true,
emitCss: true,
preprocess: true,
// legacy — we might want to remove/change these in a future version
onwarn: true,
shared: true
};
function tryRequire(id) {
try {
return require(id);
} catch (err) {
return null;
for (let key in rest) {
if (plugin_options.has(key)) continue;
console.warn(`${PREFIX} Unknown "${key}" option. Please use "compilerOptions" for any Svelte compiler configuration.`);
}
}
function tryResolve(pkg, importer) {
try {
return relative.resolve(pkg, importer);
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') return null;
if (err.code === 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
pkg_export_errors.add(pkg.replace(/\/package.json$/, ''));
return null;
}
throw err;
}
}
// [filename]:[chunk]
const cache_emit = new Map;
const { onwarn, emitCss=true } = rest;
class CssWriter {
constructor(code, filename, map, warn, toAsset) {
this.code = code;
this.filename = filename;
this.emit = toAsset;
this.warn = warn;
this.map = {
version: 3,
file: null,
sources: map.sources,
sourcesContent: map.sourcesContent,
names: [],
mappings: map.mappings
};
}
write(dest = this.filename, map = true) {
const basename = path.basename(dest);
if (map) {
this.emit(dest, `${this.code}\n/*# sourceMappingURL=${basename}.map */`);
this.emit(`${dest}.map`, JSON.stringify({
version: 3,
file: basename,
sources: this.map.sources.map(source => path.relative(path.dirname(dest), source)),
sourcesContent: this.map.sourcesContent,
names: [],
mappings: this.map.mappings
}, null, 2));
} else {
this.emit(dest, this.code);
if (emitCss) {
if (compilerOptions.css) {
console.warn(`${PREFIX} Forcing \`"compilerOptions.css": false\` because "emitCss" was truthy.`);
}
compilerOptions.css = false;
}
toString() {
this.warn('[DEPRECATION] As of rollup-plugin-svelte@3, the argument to the `css` function is an object, not a string — use `css.write(file)`. Consult the documentation for more information: https://github.com/rollup/rollup-plugin-svelte');
return this.code;
}
}
module.exports = function (options = {}) {
let { compile, preprocess, version } = options.svelte || autoload();
if (typeof version === 'string') version = to_major(version);
const filter = createFilter(options.include, options.exclude);
const extensions = options.extensions || ['.html', '.svelte'];
const fixed_options = {};
Object.keys(options).forEach(key => {
// add all options except include, exclude, extensions, and shared
if (pluginOptions[key]) return;
fixed_options[key] = options[key];
});
if (version >= 3) {
fixed_options.format = 'esm';
fixed_options.sveltePath = options.sveltePath || 'svelte';
} else {
fixed_options.format = 'es';
fixed_options.shared = require.resolve(options.shared || 'svelte/shared.js');
}
// handle CSS extraction
if ('css' in options) {
if (typeof options.css !== 'function' && typeof options.css !== 'boolean') {
throw new Error('options.css must be a boolean or a function');
}
}
let css = options.css && typeof options.css === 'function'
? options.css
: null;
// A map from css filename to css contents
// If css: true we output all contents
// If emitCss: true we virtually resolve these imports
const cssLookup = new Map();
if (css || options.emitCss) {
fixed_options.css = false;
}
return {

@@ -153,200 +45,95 @@ name: 'svelte',

/**
* Returns CSS contents for an id
* Resolve an import's full filepath.
*/
load(id) {
if (!cssLookup.has(id)) return null;
return cssLookup.get(id);
},
/**
* Returns id for import
*/
resolveId(importee, importer) {
if (cssLookup.has(importee)) { return importee; }
if (!importer || importee[0] === '.' || importee[0] === '\0' || path.isAbsolute(importee))
return null;
if (cache_emit.has(importee)) return importee;
if (!importer || importee[0] === '.' || importee[0] === '\0' || path.isAbsolute(importee)) return null;
// if this is a bare import, see if there's a valid pkg.svelte
const parts = importee.split('/');
let name = parts.shift();
if (name[0] === '@') name += `/${parts.shift()}`;
const resolved = tryResolve(
`${name}/package.json`,
path.dirname(importer)
);
if (!resolved) return null;
const pkg = tryRequire(resolved);
if (!pkg) return null;
let dir, pkg, name = parts.shift();
if (name[0] === '@') {
name += `/${parts.shift()}`;
}
const dir = path.dirname(resolved);
if (parts.length === 0) {
// use pkg.svelte
if (pkg.svelte) {
return path.resolve(dir, pkg.svelte);
try {
const file = `${name}/package.json`;
const resolved = relative.resolve(file, path.dirname(importer));
dir = path.dirname(resolved);
pkg = require(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;
}
} else {
if (pkg['svelte.root']) {
// TODO remove this. it's weird and unnecessary
const sub = path.resolve(dir, pkg['svelte.root'], parts.join('/'));
if (existsSync(sub)) return sub;
}
throw err;
}
// use pkg.svelte
if (parts.length === 0 && pkg.svelte) {
return path.resolve(dir, pkg.svelte);
}
},
/**
* Transforms a .svelte file into a .js file
* Adds a static import for virtual css file when emitCss: true
* Returns CSS contents for a file, if ours
*/
transform(code, id) {
load(id) {
return cache_emit.get(id) || null;
},
/**
* Transforms a `.svelte` file into a `.js` file.
* NOTE: If `emitCss`, append static `import` to virtual CSS file.
*/
async transform(code, id) {
if (!filter(id)) return null;
const extension = path.extname(id);
if (!~extensions.indexOf(extension)) return null;
const dependencies = [];
let preprocessPromise;
if (options.preprocess) {
if (version < 3) {
const preprocessOptions = {};
for (const key in options.preprocess) {
preprocessOptions[key] = (...args) => {
return Promise.resolve(options.preprocess[key](...args)).then(
resp => {
if (resp && resp.dependencies) {
dependencies.push(...resp.dependencies);
}
return resp;
}
);
};
}
preprocessPromise = preprocess(
code,
Object.assign(preprocessOptions, { filename: id })
).then(code => code.toString());
} else {
preprocessPromise = preprocess(code, options.preprocess, {
filename: id
}).then(processed => {
if (processed.dependencies) {
dependencies.push(...processed.dependencies);
}
return processed.toString();
});
}
} else {
preprocessPromise = Promise.resolve(code);
const filename = path.relative(process.cwd(), id);
if (rest.preprocess) {
const processed = await preprocess(code, rest.preprocess, { filename });
if (processed.dependencies) dependencies.push(...processed.dependencies);
code = processed.code;
}
return preprocessPromise.then(code => {
let warnings = [];
const compiled = compile(code, { ...compilerOptions, filename });
const base_options = version < 3
? {
onwarn: warning => warnings.push(warning)
}
: {};
(compiled.warnings || []).forEach(warning => {
if (!emitCss && warning.code === 'css-unused-selector') return;
if (onwarn) onwarn(warning, this.warn);
else this.warn(warning);
});
const compiled = compile(
code,
Object.assign(base_options, fixed_options, {
filename: id
}, version >= 3 ? null : {
name: capitalize(sanitize(id))
})
);
if (emitCss && compiled.css.code) {
const fname = id.replace(new RegExp(`\\${extension}$`), '.css');
compiled.js.code += `\nimport ${JSON.stringify(fname)};\n`;
cache_emit.set(fname, compiled.css);
}
if (version >= 3) warnings = compiled.warnings || compiled.stats.warnings;
if (this.addWatchFile) {
dependencies.forEach(this.addWatchFile);
} else {
compiled.js.dependencies = dependencies;
}
warnings.forEach(warning => {
if ((!options.css && !options.emitCss) && warning.code === 'css-unused-selector') return;
return compiled.js;
},
if (options.onwarn) {
options.onwarn(warning, warning => this.warn(warning));
} else {
this.warn(warning);
}
});
if ((css || options.emitCss) && compiled.css.code) {
let fname = id.replace(new RegExp(`\\${extension}$`), '.css');
if (options.emitCss) {
const source_map_comment = `/*# sourceMappingURL=${compiled.css.map.toUrl()} */`;
compiled.css.code += `\n${source_map_comment}`;
compiled.js.code += `\nimport ${JSON.stringify(fname)};\n`;
}
cssLookup.set(fname, compiled.css);
}
if (this.addWatchFile) {
dependencies.forEach(dependency => this.addWatchFile(dependency));
} else {
compiled.js.dependencies = dependencies;
}
return compiled.js;
});
},
/**
* If css: true then outputs a single file with all CSS bundled together
* All resolutions done; display warnings wrt `package.json` access.
*/
generateBundle(options, bundle) {
if (css) {
// TODO would be nice if there was a more idiomatic way to do this in Rollup
let result = '';
const mappings = [];
const sources = [];
const sourcesContent = [];
const chunks = Array.from(cssLookup.keys()).sort().map(key => cssLookup.get(key));
for (let chunk of chunks) {
if (!chunk.code) continue;
result += chunk.code + '\n';
if (chunk.map) {
const i = sources.length;
sources.push(chunk.map.sources[0]);
sourcesContent.push(chunk.map.sourcesContent[0]);
const decoded = decode(chunk.map.mappings);
if (i > 0) {
decoded.forEach(line => {
line.forEach(segment => {
segment[1] = i;
});
});
}
mappings.push(...decoded);
}
}
const filename = Object.keys(bundle)[0].split('.').shift() + '.css';
const writer = new CssWriter(result, filename, {
sources,
sourcesContent,
mappings: encode(mappings)
}, this.warn, (fileName, source) => {
this.emitFile({ type: 'asset', fileName, source });
});
css(writer);
generateBundle() {
if (pkg_export_errors.size > 0) {
console.warn(`\n${PREFIX} The following packages did not export their \`package.json\` file so we could not check the "svelte" field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.\n`);
console.warn(Array.from(pkg_export_errors, s => `- ${s}`).join('\n') + '\n');
}
if (pkg_export_errors.size < 1) return;
console.warn('\nrollup-plugin-svelte: The following packages did not export their `package.json` file so we could not check the `svelte` field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.\n');
console.warn(Array.from(pkg_export_errors).map(s => `- ${s}`).join('\n') + '\n');
}
};
};
{
"version": "7.0.0",
"name": "rollup-plugin-svelte",
"version": "6.1.1",
"description": "Compile Svelte components with Rollup",
"repository": "sveltejs/rollup-plugin-svelte",
"types": "index.d.ts",
"main": "index.js",
"types": "index.d.ts",
"license": "MIT",
"bugs": {
"url": "https://github.com/sveltejs/rollup-plugin-svelte/issues"
},
"files": [

@@ -13,2 +18,3 @@ "index.js",

],
"author": "Rich Harris",
"scripts": {

@@ -19,17 +25,16 @@ "lint": "eslint index.js",

},
"repository": "sveltejs/rollup-plugin-svelte",
"keywords": [
"svelte",
"rollup"
],
"author": "Rich Harris",
"license": "MIT",
"bugs": {
"url": "https://github.com/sveltejs/rollup-plugin-svelte/issues"
"engines": {
"node": ">=10"
},
"homepage": "https://github.com/sveltejs/rollup-plugin-svelte#README",
"dependencies": {
"require-relative": "^0.8.7",
"rollup-pluginutils": "^2.8.2"
},
"peerDependencies": {
"svelte": ">=3.5.0",
"rollup": ">=2.0.0"
},
"devDependencies": {
"eslint": "^6.8.0",
"locate-character": "^2.0.5",
"rollup": "^1.32.1",
"rollup": "^2.30.0",
"sander": "^0.6.0",

@@ -40,11 +45,6 @@ "source-map": "^0.7.3",

},
"dependencies": {
"require-relative": "^0.8.7",
"rollup-pluginutils": "^2.8.2",
"sourcemap-codec": "^1.4.8"
},
"peerDependencies": {
"svelte": "*",
"rollup": ">=1.19.2"
}
"keywords": [
"svelte",
"rollup"
]
}

@@ -1,2 +0,2 @@

# rollup-plugin-svelte ![CI](https://github.com/sveltejs/rollup-plugin-svelte/workflows/CI/badge.svg?branch=6.x)
# rollup-plugin-svelte [![CI](https://github.com/sveltejs/rollup-plugin-svelte/workflows/CI/badge.svg)](https://github.com/sveltejs/rollup-plugin-svelte/actions)

@@ -20,2 +20,3 @@ Compile Svelte components.

import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';

@@ -30,3 +31,3 @@ export default {

svelte({
// By default, all .svelte and .html files are compiled
// By default, all ".svelte" files are compiled
extensions: ['.my-custom-extension'],

@@ -54,4 +55,4 @@

// Emit CSS as "files" for other plugins to process
emitCss: true,
// Emit CSS as "files" for other plugins to process. default is true
emitCss: false,

@@ -62,14 +63,2 @@ // You can optionally set 'customElement' to 'true' to compile

// Extract CSS into a single bundled file (recommended).
// See note below
css: function (css) {
console.log(css.code); // the concatenated CSS
console.log(css.map); // a sourcemap
// creates `main.css` and `main.css.map`
// using a falsy name will default to the bundle name
// — pass `false` as the second argument if you don't want the sourcemap
css.write('main.css');
},
// Warnings are normally passed straight to Rollup. You can

@@ -84,9 +73,7 @@ // optionally handle them here, for example to squelch

handler(warning);
},
// Pass in a specific version of Svelte, e.g. if you use
// npm aliases to install multiple versions you can import
// a specific version. Assume "svelte1" is `svelte@1.x` alias.
svelte: require('svelte1')
})
}
}),
// see NOTICE below
resolve({ browser: true }),
// ...
]

@@ -96,3 +83,5 @@ }

> **NOTICE:** You will need additional Rollup plugins. <br>Alone, this plugin translates Svelte components into CSS and JavaScript files. <br>You will need to include [`@rollup/plugin-node-resolve`](https://www.npmjs.com/package/@rollup/plugin-node-resolve) – and probably [`@rollup/plugin-commonjs`](https://www.npmjs.com/package/@rollup/plugin-commonjs) – in your Rollup config.
## Preprocessing and dependencies

@@ -132,13 +121,8 @@

If your Svelte components contain `<style>` tags, by default the compiler will add JavaScript that injects those styles into the page when the component is rendered. That's not ideal, because it adds weight to your JavaScript, prevents styles from being fetched in parallel with your code, and can even cause CSP violations.
By default (when `emitCss: true`) the CSS styles will be emitted into a virtual file, allowing another Rollup plugin – for example, [`rollup-plugin-css-only`](https://www.npmjs.com/package/rollup-plugin-css-only), [`rollup-plugin-postcss`](https://www.npmjs.com/package/rollup-plugin-postcss), etc. – to take responsibility for the new stylesheet. In fact, emitting CSS files _requires_ that you use a Rollup plugin to handle the CSS. Otherwise, your build(s) will fail! This is because this plugin will add an `import` statement to import the emitted CSS file. It's not valid JS to import a CSS file into a JS file, but it allows the CSS to be linked to its respective JS file and is a common pattern that other Rollup CSS plugins know how to handle.
A better option is to extract the CSS into a separate file. Using the `css` option as shown above would cause a `public/main.css` file to be generated each time the bundle is built (or rebuilt, if you're using rollup-watch), with the normal scoping rules applied.
If you set `emitCss: false` and your Svelte components contain `<style>` tags, the compiler will add JavaScript that injects those styles into the page when the component is rendered. That's not the default, because it adds weight to your JavaScript, prevents styles from being fetched in parallel with your code, and can even cause CSP violations.
If you have other plugins processing your CSS (e.g. rollup-plugin-scss), and want your styles passed through to them to be bundled together, you can use `emitCss: true`.
Alternatively, if you're handling styles in some other way and just want to prevent the CSS being added to your JavaScript bundle, use `css: false`.
## License
MIT
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc