leecjson / ref-loader

A webpack loader that will create dependencies between any files manually
MIT License
7 stars 2 forks source link

Anchor tag rewriting without passing object to loader #2

Open benjaminpreiss opened 4 years ago

benjaminpreiss commented 4 years ago

Is there any possibility to process anchor tags in an HTML file before handing it to html-loader? I would like to rewrite relative paths of linked HTML-files in anchor tags...

leecjson commented 4 years ago

@benjaminpreiss Can you show some examples to help me know what are you going to make?

benjaminpreiss commented 4 years ago

yes, absolutely:

file structure:

src
|_  html
|   |_  index.html
|   |_  site2.html
|_  js
|   |_  index.js

node_modules

dist
|_  index.html
|_  html
|   |_  site2.html
|_  js
|   |_  index.bundle.js

webpack.config.js

postcss.config.js

index.html

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>...</title>
  <meta name="description" content="">
  <meta name="author" content="">
</head>

<body>
<a href="./site2.html"></a>
</body>
</html>

site2.html

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>...</title>
  <meta name="description" content="">
  <meta name="author" content="">
</head>

<body>
<a href="./index.html"></a>
</body>
</html>

index.js

console.log(test);

webpack.config.js

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

module.exports = {
  entry: {
    index: ['./src/js/index.js'],
  },
  mode: 'development',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/html/index.html',
      filename: './index.html',
    }),
    new HtmlWebpackPlugin({
      template: './src/html/site2.html',
      filename: './html/site2.html',
    }),
  ],
  devtool: 'source-map',
  module: {
    rules: [ 
      {
        test: /\.html$/,
        use: [
            {
              loader: "html-loader",
              }
            }
        ]
      },
      {
          test: /\.js$/,
          exclude: /node_modules/,
          use: "babel-loader"
      }
    ]
  },
};

Now, I would like the paths in <a href="..."></a> to be rewritten accoring to th filestructure in dist

benjaminpreiss commented 4 years ago

But I do not want to trigger a loader when rewriting the url, because that would result in an endless cycle?

leecjson commented 4 years ago

Commonly you can't create dependence to HtmlWebpackPlugin's html file. But you can create dependence from HtmlWebpackPlugin's html file to any othor files via 'html-loader' or 'ref-loader'.