If a svelte file contains some language other than html
, css
or javascript
, coc-svelte
needs to know how to preprocess it. This can be achieved by creating a svelte.config.js
file at the root of your project which exports a svelte options object (similar to svelte-loader
and rollup-plugin-svelte
). It's recommended to use the official svelte-preprocess package which can handle many languages.
NOTE: you cannot use the new
import x from y
andexport const
/export default
syntax insvelte.config.js
.
// svelte.config.js
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
preprocess: sveltePreprocess(),
};
It's also necessary to add a type="text/language-name"
or lang="language-name"
to your style
and script
tags, which defines how that code should be interpreted by the extension.
<div>
<h1>Hello, world!</h1>
</div>
<style type="text/scss">
div {
h1 {
color: red;
}
}
</style>
If you use svelte-preprocess
and define the defaults inside svelte.config.js
, you can in some cases omit the type
/lang
attributes. While these defaults get picked up by the language server, this may break your syntax highlighting and your code is no longer colored the right way, so use with caution - we recommend to always type the attributes. Reason: we have to tell VSCode which part of the Svelte file is written in which language through providing static regexes, which rely on the type
/lang
attribute.
const sveltePreprocess = require('svelte-preprocess');
module.exports = {
preprocess: sveltePreprocess({
defaults: {
script: 'typescript', // <-- now you can just write <script>let typingsAllowed: string;</script>
},
}),
};
Most of the preprocessor settings you write inside your svelte.config.js
is likely duplicated in your build config. Here's how to deduplicate it (using rollup as an example):
// svelte.config.js:
const sveltePreprocess = require('svelte-preprocess');
// using sourceMap as an example, but could be anything you need dynamically
function createPreprocessors(sourceMap) {
return sveltePreprocess({
sourceMap,
// ... your settings
});
}
module.exports = {
preprocess: createPreprocessors(true),
createPreprocessors,
};
// rollup.config.js:
// ...
const createPreprocessors = require('./svelte.config').createPreprocessors;
const production = !process.env.ROLLUP_WATCH;
export default {
// ...
plugins: [
// ...
svelte({
// ...
preprocess: createPreprocessors(!production),
}),
// ...
],
};
You will need to tell coc-svelte to restart the svelte language server in order to pick up a new configuration: :CocCommand svelte.restartLanguageServer
.