andywer / threads-plugin

📦 Makes your threads.js code build with webpack out of the box.
Apache License 2.0
28 stars 6 forks source link

webpack-config, electron and typescript #35

Open softwarecurator opened 3 years ago

softwarecurator commented 3 years ago

getting the warning

WARNING in No instantiations of threads.js workers found.
Please check that:
  1. You have configured Babel / TypeScript to not transpile ES modules
  2. You import `Worker` from `threads` where you use it

my webpack

const lodash = require("lodash");
const CopyPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ThreadsPlugin = require("threads-plugin");
const path = require("path");
const webpack = require("webpack");

function srcPaths(src) {
  return path.join(__dirname, src);
}

const isEnvProduction = process.env.NODE_ENV === "production";
const isEnvDevelopment = process.env.NODE_ENV === "development";

// #region Common settings
const commonConfig = {
  devtool: isEnvDevelopment ? "source-map" : false,
  mode: isEnvProduction ? "production" : "development",
  output: { path: srcPaths("dist") },
  devServer: {
    port: 8080,
    contentBase: srcPaths("dist"),
    writeToDisk: true,
    hot: true,
    open: true,
  },
  node: { __dirname: false, __filename: false },
  resolve: {
    alias: {
      _: srcPaths("src"),
      _main: srcPaths("src/main"),
      _models: srcPaths("src/models"),
      _public: srcPaths("public"),
      _renderer: srcPaths("src/renderer"),
      _utils: srcPaths("src/utils"),
    },
    extensions: [".js", ".json", ".ts", ".tsx"],
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: srcPaths("src"),
        use: [
          "thread-loader",
          // your expensive loader (e.g babel-loader)
        ],
      },
      {
        test: /\.(ts|tsx|js)$/,
        exclude: /node_modules/,
        loader: "ts-loader",
      },
      {
        test: /\.(scss|css)$/,
        use: ["style-loader", "css-loader", "sass-loader"],
      },
      {
        test: /\.(jpg|png|svg|ico|icns)$/,
        loader: "file-loader",
        options: {
          name: "[path][name].[ext]",
        },
      },
    ],
  },
  plugins: [
    new ThreadsPlugin({
      target: "electron-node-worker",
      globalObject: "self",
      plugins: [
        // A string here will copy the named plugin from your configuration:
        "HtmlWebpackPlugin",
      ],
    }),
  ],
};
// #endregion

const mainConfig = lodash.cloneDeep(commonConfig);
mainConfig.entry = "./src/main/main.ts";
mainConfig.target = "electron-main";
mainConfig.output.filename = "main.bundle.js";
mainConfig.plugins = [
  ...mainConfig.plugins,
  new CopyPlugin({
    patterns: [
      {
        from: "package.json",
        to: "package.json",
        transform: (content, _path) => {
          // eslint-disable-line no-unused-vars
          const jsonContent = JSON.parse(content);

          delete jsonContent.devDependencies;
          delete jsonContent.scripts;
          delete jsonContent.build;

          jsonContent.main = "./main.bundle.js";
          jsonContent.scripts = { start: "electron ./main.bundle.js" };
          jsonContent.postinstall = "electron-builder install-app-deps";

          return JSON.stringify(jsonContent, undefined, 2);
        },
      },
    ],
  }),
  new webpack.HotModuleReplacementPlugin(),
];

const rendererConfig = lodash.cloneDeep(commonConfig);
rendererConfig.entry = [
  "react-hot-loader/patch",
  "./src/renderer/renderer.tsx",
];
rendererConfig.target = "electron-renderer";
rendererConfig.output.filename = "renderer.bundle.js";
rendererConfig.plugins = [
  ...rendererConfig.plugins,
  new webpack.HotModuleReplacementPlugin(),
  new HtmlWebpackPlugin({
    template: path.resolve(__dirname, "./public/index.html"),
  }),
];

module.exports = [mainConfig, rendererConfig];

How im calling threads

async function test() {
  const auth = await spawn(new Worker("./workers/worker-scripts.ts", { type: 'module' }))
  const hashed = await auth.hashPassword("Super secret password", "1234")

  console.log("Hashed password:", hashed)

  await Thread.terminate(auth)
}

test()

and my worker

// workers/auth.js
import sha256 from "js-sha256";
import { expose } from "threads/worker";

expose({
  hashPassword(password, salt) {
    return 'sha256(password + salt)';
  },
});

The issue is it it seems like it's not searching or compiling and searching correctly since this is the error

 Cannot find module '/dist/workers/worker-scripts.ts'
andywer commented 3 years ago

Hi @josephriosIO.

Based on your sample code you are instantiating new Worker(…) without having imported the threads.js Worker import { Worker } from "threads". The webpack plugin will only handle worker instantiations of threads.js' Workers.

Hope that helps.