sveltejs / svelte-loader

Webpack loader for svelte components.
MIT License
594 stars 73 forks source link

Runes in non-Svelte files failing on runes not defined #239

Closed egilsster closed 1 month ago

egilsster commented 2 months ago

Trying out Svelte 5 on a fairly sized project and got blocked by this problem. I am migrating a writable store to a little API wrapping some state with the $state rune, however, if I define the object in a thing.svelte.ts file the app crashes on an error stating that $state is not defined. I suspect this has something to do with how webpack bundles these files together with different, since the same store works fine when defined within a regular Svelte file.

I am using swc to build ts and js files and the latest svelte compiler to build the svelte files. I've put up a minimal reproduction project here https://github.com/egilsster/runes-repro

It's my best guess that the problem lies within svelte-loader.

non25 commented 1 month ago

Have you tried to add svelte-loader for svelte.js files also so it runs the compiler? I don't think anything else except svelte compiler understands that magic. :grin:

dummdidumm commented 1 month ago

This config works:

/* eslint-disable */

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = ({ mode = "production" }) => {
  const config = {
    mode,
    entry: {
      "runes-repro": path.resolve(__dirname, "src/runes-repro.ts"),
    },
    output: {
      path: path.resolve(__dirname, "dist"),
      filename: "[name].js",
      clean: true,
    },
    resolve: {
      extensions: [".mjs", ".js", ".ts", ".svelte"],
      conditionNames: ["svelte", "browser", "import", "require", "node"],
    },
    module: {
      rules: [
        {
          test: /\.svg/,
          type: "asset/source",
        },
+        {
+          test: /\.svelte\.ts$/,
+          exclude: /node_modules/,
+          use: [{ loader: "swc-loader" }, { loader: "svelte-loader" }],
+        },
        {
          test: /\.(js|ts)x?$/,
          exclude: /node_modules/,
          use: [{ loader: "swc-loader" }],
        },
        {
          test: /\.m?js/,
          resolve: {
            fullySpecified: false,
          },
        },
        {
-          test: /\.(html|svelte)$/,
+          test: /\.(html|svelte|svelte\.js)$/,
          use: "svelte-loader",
        },
      ],
    },
    plugins: [new HtmlWebpackPlugin()],
    devtool: "source-map",
  };

  return config;
};

Adding something to the documentation

egilsster commented 1 month ago

Thanks! That did the trick 🙂