Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I move JS code out of Svelte component file to other file js file?

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.

like image 937
Harshal Patil Avatar asked Aug 08 '19 07:08

Harshal Patil


People also ask

Can we put JavaScript in a separate file?

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.

What do I do with a .JS file?

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.


1 Answers

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]};
        }
      }
    }
  })
]
like image 198
Rich Harris Avatar answered Oct 20 '22 17:10

Rich Harris