简体   繁体   中英

Webpack extract js with html literal in html file

I have a js file like this

const link = () => {
   return '<p>my text </p>'
}

I want to use webpack to return an html file with :

<p>my text </p>

Which loader i need to use ? Do you have an example webpack config ?

Thanks

It sounds like you would like to create an HTML file from your js file.

If would look for 'static site generators' much like this one:

If you are not using a . framework like react or angular, you may have to use a templating language instead like handlebars or ejs .

here are some examples of how to start putting the site together:

your index.js file might look more like :

module.exports = function(locals) {
  return locals.template({ html: '<h1>' + locals.path + '</h1>' });
};

Which would be combined with a template.ejs file like :

<html>
  <body>
    <%- html %>
  </body>
</html>

and a wabpack config file like:

var StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin');
var StatsWriterPlugin = require("webpack-stats-plugin").StatsWriterPlugin;
var ejs = require('ejs');
var fs = require('fs');

var template = ejs.compile(fs.readFileSync(__dirname + '/template.ejs', 'utf-8'))

var paths = [
  '/',
  '/foo',
  '/foo/bar'
];

module.exports = {
  entry: __dirname + '/index.js',

  output: {
    filename: 'index.js',
    path: __dirname + '/actual-output',
    libraryTarget: 'umd'
  },

  plugins: [
    new StaticSiteGeneratorPlugin({
      paths: paths,
      locals: {
        template: template
      }
    }),
    new StatsWriterPlugin() // Causes the asset's `size` method to be called
  ]
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM