DEV Community

Sajal Arora
Sajal Arora

Posted on

6 5

Unable to create webpack bundle for chrome extension

I am fairly new to chrome extension development. I am trying to use webpack for bundling since I am using node modules. The entry file in my case is service-worker.js since that's where the modules and packages are being imported. I end up with the following error on build.

ReferenceError: window is not defined
    at shouldUseActiveX (service-worker.js:870)
    at createHTMLParser (service-worker.js:843)
    at Object../node_modules/turndown/lib/turndown.browser.es.js (service-worker.js:877)
    at __webpack_require__ (service-worker.js:1594)
    at Object../src/service/save-url-section.js (service-worker.js:1372)
    at __webpack_require__ (service-worker.js:1594)
    at service-worker.js:1658
    at service-worker.js:1887
    at service-worker.js:1890
Enter fullscreen mode Exit fullscreen mode

Yes, I know that this question had been asked several times before for different scenarios. The window object in background is not allowed. But in my situation I have

       chrome.scripting
          .executeScript({
            target: { tabId: tabId },
            files: ["./foreground/saveUrl.js"],
          })
Enter fullscreen mode Exit fullscreen mode

in my service-worker.js. Now I am assuming that the path mentioned in the files array is getting resolved and bringing all the window into the bundled file which is why I am ending up the above error. I really need help here.

BTW this is my webpack config

var options = {
  mode: process.env.NODE_ENV || "development",
  entry: {
    // popup: path.join(__dirname, "src", "popup", "popup.js"),
    "service-worker": path.join(__dirname, "src", "service-worker.js"),
  },
  output: {
    globalObject: "this",
    path: path.join(__dirname, "dist"),
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
        exclude: /node_modules/,
      },
      {
        test: new RegExp(".(" + fileExtensions.join("|") + ")$"),
        use: [
          {
            loader: "file-loader",
          },
        ],
        exclude: /node_modules/,
      },
      {
        test: /\.html$/,
        loader: "html-loader",
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ["*", ".js"],
    // alias: alias,
  },
  plugins: [
    // clean the build folder
    new CleanWebpackPlugin({
      cleanStaleWebpackAssets: false,
    }),
    // expose and write the allowed env vars on the compiled bundle
    new webpack.EnvironmentPlugin(["NODE_ENV"]),
    new CopyWebpackPlugin({
      patterns: [
        { from: "./src/logo", to: "./src/logo" },
        { from: "./src/foreground", to: "./src/foreground" },
        { from: "./src/settings", to: "./src/settings" },
        { from: "./src/popup", to: "./src/popup" },
        { from: "./src/utils", to: "./src/utils" },
        {
          from: "./manifest.json",
          transform: function (content, path) {
            // generates the manifest file using the package.json informations
            return Buffer.from(
              JSON.stringify({
                description:
                  process.env.npm_package_description || "Notion Pro Clipper",
                version: process.env.npm_package_version || 3,
                background: {
                  "service-worker": "./service-worker.js",
                },
                ...JSON.parse(content.toString()),
              })
            );
          },
        },
      ],
    }),
    // new HtmlWebpackPlugin({
    //   template: path.join(__dirname, "src", "popup", "index.html"),
    //   filename: "popup.html",
    //   chunks: ["popup"],
    // }),
    // new HtmlWebpackPlugin({
    //   template: path.join(__dirname, "src", "settings/settings.html"),
    //   filename: "settings.html",
    //   chunks: ["options"],
    // }),
    // new HtmlWebpackPlugin({
    //   template: path.join(__dirname, "src", "background.html"),
    //   filename: "background.html",
    //   chunks: ["background"]
    // }),
    new WriteFilePlugin(),
  ],
};
Enter fullscreen mode Exit fullscreen mode

Image of Bright Data

Scale Your Data Needs Effortlessly – Expand your data handling capacities seamlessly.

Leverage our scalable solutions to meet your growing data demands without compromising performance.

Scale Effortlessly

Top comments (1)

Collapse
 
mrinasugosh profile image
Mrinalini Sugosh (Mrina)

@sajal_arora_bf838c9eb6a01 Do you have this in a repo to review the source code for service-worker.js?

Based on this, my best bet here is that service-worker.js tries to use window object at import time.
I would suggest using something like lazy-loading and dynamically import. This should prevent this error. What are the imports in your file?

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay