I am currently exploring Bucklescript/ReasonML with Svelte 3 for my next project. Typical Svelte component is a .svelte
file:
<script>
let name = 'world';
</script>
<h1>Hello world!</h1>
Instead, can I have script
tag with src
or equivalent to keep JS code in a separate file?
<script src='./some-file.js'></script>
By moving the js
code to a separate file, the target of the Bucklescript compiler (which is a JS file) could be used for the component.
Vue.js already supports this with their SFC .vue
file.
On a side note: I could use Vue.js for this but the presence Virtual DOM is problematic for legacy codebase. And, Svelte is diminishing at runtime and thus very much desirable. Also, the use
this
in Vue makes things awkward in Ocaml/Reason.
We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code.
To use a JS file, you include it in the HTML document. You use the link tag to include the file as shown below. The src attribute of the script tag contains the path to the JS file. By doing this, the JS functionality is added to the HTML document.
This is possible with the svelte.preprocess API, which you'd most commonly reach via the preprocess
option in rollup-plugin-svelte or svelte-loader. Something like this should work (though I haven't tested it):
const path = require( 'path' )
const fs = require( 'fs' )
...
plugins: [
svelte({
// ...
preprocess: {
script: ({ content, attributes, filename }) => {
if ( 'string' === typeof attributes.src ) {
const file = path.resolve(path.dirname(filename), attributes.src);
const code = fs.readFileSync(file, 'utf-8');
return {code, dependencies: [file]};
}
}
}
})
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With