sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
78.19k stars 4.09k forks source link

How to include external dependencies? #168

Closed mmjmanders closed 7 years ago

mmjmanders commented 7 years ago

I followed the instructions on https://svelte.technology/guide#helpers. How do I make sure that the leftPad function is available in the component when accessing this through a browser? Or is this purely to use with e.g. webpack?

Rich-Harris commented 7 years ago

In the glorious future that's just around the corner, import will work natively in browsers and this will 'just work' (as long as the browser knows where to find left-pad – not entirely sure how that's going to work).

Sadly, in the meantime you will indeed have to use a bundler like Webpack. The compiler can output one of five different formats:

In the iife case, the expectation is that the dependency already exists on the page. left-pad is actually a bad example because it only works in CommonJS environments, but if we pretend that it works as a <script> tag then it'd look something like this:

<script src='https://unpkg.com/left-pad'></script>
<script src='MyComponent.js'></script>
<script>
  var app = new MyComponent({...});
</script>

The compiler would guess from your source code that the left-pad module ID corresponds to the leftPad global, but you can remove the ambiguity by configuring it:

var compiled = svelte.compile( input, {
  format: 'iife',
  globals: {
    'left-pad': 'leftPad'
  }
});

Of course, this is all rather cumbersome and frustrating – you're better off using a bundler which will take care of all the configuration nonsense, at least until modules are natively supported widely enough (hopefully in the next few months!).

ianengelbrecht commented 4 years ago

May I raise this again? How do we use leftPad in Svelte3 using import?

antony commented 4 years ago

@ianengelbrecht you don't need leftPad any more, see https://www.npmjs.com/package/left-pad

You can import any module into Svelte simply using a regular import variable from 'moduleName' as you would in regular es6.

Please direct further support questions to chat. Github issues is better suited for bug reports and feature requests.