Unable to import rehype-autolink-headings
in my webpack config (commonjs)
COde:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const rehype=require("rehype-autolink-headings") // <----- PROBLEM is HERE
const isProduction = process.env.NODE_ENV == "production";
const stylesHandler = isProduction
? MiniCssExtractPlugin.loader
: "style-loader";
const config = {
entry: "./src/index.tsx",
output: {
path: path.resolve(__dirname, "build"),
publicPath: '/'
},
devServer: {
open: true,
host: "localhost",
historyApiFallback: true
},
plugins: [
new HtmlWebpackPlugin({
template: "index.html",
}),
new CopyPlugin({
patterns: [
{ from: "public", to: "./" },
],
}),
// Add your plugins here
// Learn more about plugins from https://webpack.js.org/configuration/plugins/
],
module: {
rules: [
// `js` and `jsx` files are parsed using `babel`
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
// `ts` and `tsx` files are parsed using `ts-loader`
{
test: /\.(ts|tsx)$/,
loader: "ts-loader",
},
{
test: /\.mdx?$/,
use: [
{
loader: '@mdx-js/loader',
/** @type {import('@mdx-js/loader').Options} */
options: {
rehypePlugins: [rehype],
}
}
]
},
{
test: /\.css$/i,
use: [stylesHandler, "css-loader"],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: "asset",
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".jsx", ".js", "..."],
},
};
module.exports = () => {
if (isProduction) {
config.mode = "production";
config.plugins.push(new MiniCssExtractPlugin());
} else {
config.mode = "development";
}
return config;
};
Getting this error:
[webpack-cli] Failed to load 'webpack.config.js' config
[webpack-cli] Error [ERR_REQUIRE_ESM]: require() of ES Module node_modules\rehype-autolink-headings\index.js from webpack.config.js not supported.
My webpack versions:
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
How to make it work> I was trying a huge amount of approaches
Probably the easiest way is to use native esm
for webpack
configuration cause it has been supported this for a while.
It means you need to fix your configuration a bit where to require
and export
your module and then rename the configuration file with .mjs
extension to make sure webpack
understands this is written in esm
(webpack.config.mjs
)
BTW, it's even better to write it in TS too which is addressed clearly how many languages that a configuration can be written here