rb.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const fs = require('fs');
  2. const path = require('path');
  3. const cheerio = require('cheerio');
  4. const webpack = require('webpack');
  5. const webpackDevServer = require('webpack-dev-server');
  6. const webpackBaseConfig = require('./webpack.base.config');
  7. const getEntry = require('./getEntry');
  8. const writeFile = require('./writeFile');
  9. const config = require('../new-config.json');
  10. let entries = getEntry();
  11. let libEntries = getEntry('lib');
  12. let targetPath = webpackBaseConfig.output.path;
  13. createHtml();
  14. let pageCompiler = webpack({
  15. ...webpackBaseConfig,
  16. entry: entries
  17. });
  18. let libCompiler = webpack({
  19. ...webpackBaseConfig,
  20. entry: libEntries
  21. });
  22. libCompiler.run(function(err, stat) {
  23. if(err) {
  24. console.log(err);
  25. }
  26. let server = new webpackDevServer(pageCompiler, {
  27. contentBase: path.join(__dirname, '../dist'),
  28. proxy: config.proxy,
  29. stats: 'errors-only'
  30. });
  31. server.listen(3006, '', () => {
  32. console.log('open localhost:3006');
  33. });
  34. });
  35. function createHtml() {
  36. try {
  37. let template = fs.readFileSync(path.join(__dirname, '../index.html'), {
  38. encoding: 'utf8'
  39. });
  40. let publicPath = webpackBaseConfig.output.publicPath;
  41. Object.keys(entries).map((filePath) => {
  42. let htmlPath = filePath + '.html';
  43. let cssPath = path.join(publicPath, filePath) + '.css';
  44. let jsPath = path.join(publicPath, filePath) + '.js';
  45. let content = template;
  46. let $ = cheerio.load(content);
  47. $('head').append(`<link rel="stylesheet" href="${cssPath}" />`);
  48. $('body').append(`<script src="${jsPath}"></script>`)
  49. writeFile(targetPath, htmlPath, $.html());
  50. });
  51. }
  52. catch(e) {
  53. console.log(e);
  54. }
  55. }