Rami Chasygov
Rami Chasygov

Reputation: 2784

Set up Webpack for .ejs

I have project where I use ejs files. Only problem that I use ejs files for server side. Code below. I need set up webpack in way, that on fly it insert in index.ejs <script src="frontend/build/..."></script> and <style src="frontend/build/..."/>. Only that I know is that I should use webpack-middleware somehow. If someone have experience, please help me set up.

// webpack.config.js

import path from 'path';

import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';

const inProduction = process.argv[process.argv.length - 1]
  .match(/[a-z]+$/g)[0] === 'production';

const basic = {
  entry: {
    app: path.join(__dirname, 'frontend/source/scripts/main.js'),
  },
  output: {
    path: path.join(__dirname, 'frontend/build'),
    filename: '[name].[chunkhash].js',
  },
};

const module = {
  rules: [{
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        use: ['css-loader'],
      }),
    },
    {
      test: /\.js$/,
      use: ['babel-loader'],
      exclude: ['/node_modules'],
    },
  ],
};

const plugins = [
  new ExtractTextPlugin('[name].[contenthash].css'),
  new CleanWebpackPlugin('build'),
];

export default {
  ...basic,
  module,
  plugins,
};
<!-- index.ejs -->

<header class="header">Git Rendering</header>
   
    <main class="container">

      <% if (branches) { %>
        <%- include('branches'); %>
      <% } %>

      <% if (commits) { %>
        <%- include('commits'); %>
      <% } %>

      <% if (files) { %>
        <%- include('files'); %>
      <% } %>

      <% if (file) { %>
        <%- include('file'); %>
      <% } %>
      
    </main>

Upvotes: 3

Views: 12166

Answers (1)

lukas-reineke
lukas-reineke

Reputation: 3322

The easiest solution would be to load the files with html-webpack-plugin. You can write templates and inject your script tags.
If you just want to add your webpack entries, it will already happen automatically.

The only thing you need to watch out for is, that html-webpack-plugin uses ejs templating as well. So you will need to change either your or the plugins templating syntax.

Upvotes: 5

Related Questions