Library transpilation using Babel (and Webpack) does not work when using required

18 views Asked by At

I'm trying to transpile the marked library during bundling to make it work on old Safari. My webpack.config.js (which includes Babel settings) looks like this:

var path = require("path");

module.exports = {
    mode: "production",
    entry: "./src/index.js",
    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, "dist"),
        libraryTarget: "window",
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: "babel-loader",
                    options: {
                        presets: ["@babel/preset-env"],
                    },
                },
                exclude: {
                    and: [/node_modules/],
                    not: [/marked/],
                },
            },
        ],
    },
};

In my src files, if I do the following:

import { marked } from "marked";

// Use marked here

Then the transpilation works properly and it runs on my old Safari. However, if I do the following:

var marked = require("marked");

// Use marked here

Then the transpilation does not apply to marked, and my site breaks on Safari. So what gives? Am I missing something obvious?

My pacakge.json looks like this (no type property):

{
    ...
    "devDependencies": {
        "@babel/core": "^7.24.0",
        "@babel/preset-env": "^7.24.0",
        "babel-loader": "^9.1.3",
        "webpack": "^5.90.3",
        "webpack-cli": "^5.1.4"
        ...
    },
    "dependencies": {
        "marked": "^12.0.1",
        ...
    },
}

0

There are 0 answers