symfony / webpack-encore

A simple but powerful API for processing & compiling assets built around Webpack
https://symfony.com/doc/current/frontend.html
MIT License
2.22k stars 198 forks source link

Svelte-loader custom component and global CSS/SCSS #1112

Open kl3sk opened 2 years ago

kl3sk commented 2 years ago

Hello,

I setup Encore to use svelte-loader as such:

...
    .addLoader({
            test: /\.svelte$/,
            loader: 'svelte-loader',
            options: {
                preprocess: sveltePreprocess(),
                emitCss: true,
                compilerOptions: {
                    css: true,
                    dev: !Encore.isProduction(),
                    customElement: true,
                }
            }
        },
        {
            // required to prevent errors from Svelte on Webpack 5+, omit on Webpack 4
            test: /node_modules\/svelte\/.*\.mjs$/,
            resolve: {
                fullySpecified: false
            }
        }
    )
...
let config = Encore.getWebpackConfig()
config.resolve.mainFields = ['svelte', 'browser', 'module', 'main']
config.resolve.extensions = ['.mjs', '.js', '.svelte']

let svelte = config.module.rules.pop()
config.module.rules.unshift(svelte)

module.exports = config

Svelete works as expected if I disable customElement options.

With this option enabled, I manage to have a working custom element, unless I use styles for nested component.

As I understand, it looks like not possible to style nested components inside it.

A workaround is to use :global inside parent element, but with my configuration it doesn't work.

Is there a specific webpack config for it I failed ?

Thanks

mandrasch commented 1 year ago

Hey, do you still have the problem? I use the following config and styling worked fine for me?


const preprocess = require('svelte-preprocess');

/* ... */

  // enables Sass/SCSS support
  .enableSassLoader();

  .addLoader({
    test: /\.svelte$/,
    loader: "svelte-loader",
    options: {
      preprocess: preprocess(),
      emitCss: true,
      compilerOptions: {
        css: true,
        dev: !Encore.isProduction()
      }
    }
  }, {
    // https://github.com/symfony/webpack-encore/issues/1112
    // required to prevent errors from Svelte on Webpack 5+, omit on Webpack 4
    test: /node_modules\/svelte\/.*\.mjs$/,
    resolve: {
      fullySpecified: false
    }
  })

/* At the end */

// https://www.twilio.com/blog/develop-a-symfony-app-using-svelte-and-webpack-encore-to-manage-your-twilio-message-history 
let config = Encore.getWebpackConfig();

// https://github.com/sveltejs/svelte-loader
config.resolve = {
  alias: {
    svelte: path.resolve('node_modules', 'svelte')
  },
  extensions: ['.mjs', '.js', '.svelte'],
  mainFields: ['svelte', 'browser', 'module', 'main'],
  conditionNames: ['svelte']
};

module.exports = config;