Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use stage 3 syntax in svelte/sapper?

I want to use class property and private fields in my sapper project. Apparently they have to be preprocessed by babel right now.

I tried to add the corresponding babel plugins to rollup.config.js, only to realize a few things.

  1. the babel rollup plugin is only used in legacy mode.
  2. the server part doesn't use babel at all.

I tried to add the babel rollup plugin to the end of server plugins like this,

babel({
    extensions: ['.js', '.mjs', '.html', '.svelte'],
    runtimeHelpers: true,
    exclude: ['node_modules/@babel/**'],
    plugins: [
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-proposal-private-methods',
    ],
}),

But it doesn't seem to take effect at all.

I also added it to the client plugins (before the legacy entry), but it complained about I needed to add @babel/plugin-syntax-dynamic-import, so looks like babel has to recognize the whole syntax in order to preprocess, and I don't really want to compile dynamic import for modern browsers.

How do I enable the use of esnext syntax in sapper?

like image 578
hgl Avatar asked Mar 03 '23 16:03

hgl


1 Answers

You would need to preprocess the contents of <script>, using the preprocess option in rollup-plugin-svelte:

plugins: [
  svelte({
    // ...
    preprocess: {
      script: ({ content }) => {
        return transformWithBabel(content);
      }
    },
    // ...
  })
]

In an ideal world we'd have a ready-made preprocessor plugin for doing this; as it is, the transformWithBabel function is left as an exercise to the reader for now. Essentially it would involve import * as babel from '@babel/core' and using the Babel API directly, which I guarantee will be lots of fun.

Note that @babel/plugin-syntax-dynamic-import doesn't compile dynamic import, it only allows Babel to parse it. Without it, Babel can't generate a valid AST from the code inside <script>.

like image 128
Rich Harris Avatar answered Apr 21 '23 14:04

Rich Harris