compile-with-webpack.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import path from 'path'
  2. import webpack from 'webpack'
  3. import MemoryFS from 'memory-fs'
  4. import { RenderOptions } from 'server/create-renderer'
  5. import { createBundleRenderer } from 'server/index'
  6. import VueSSRServerPlugin from 'server/webpack-plugin/server'
  7. export function compileWithWebpack(
  8. file: string,
  9. extraConfig?: webpack.Configuration
  10. ) {
  11. const config: webpack.Configuration = {
  12. mode: 'development',
  13. entry: path.resolve(__dirname, 'fixtures', file),
  14. module: {
  15. rules: [
  16. {
  17. test: /async-.*\.js$/,
  18. loader: require.resolve('./async-loader')
  19. },
  20. {
  21. test: /\.(png|woff2|css)$/,
  22. loader: require.resolve('file-loader'),
  23. options: {
  24. name: '[name].[ext]'
  25. }
  26. }
  27. ]
  28. }
  29. }
  30. if (extraConfig) {
  31. Object.assign(config, extraConfig)
  32. }
  33. const compiler = webpack(config)
  34. const fs = new MemoryFS()
  35. compiler.outputFileSystem = fs
  36. return new Promise<MemoryFS>((resolve, reject) => {
  37. compiler.run(err => {
  38. if (err) {
  39. reject(err)
  40. } else {
  41. resolve(fs)
  42. }
  43. })
  44. })
  45. }
  46. export async function createWebpackBundleRenderer(
  47. file: string,
  48. options?: RenderOptions & { asBundle?: boolean }
  49. ) {
  50. const asBundle = !!(options && options.asBundle)
  51. if (options) delete options.asBundle
  52. const fs = await compileWithWebpack(file, {
  53. target: 'node',
  54. devtool: asBundle ? 'source-map' : false,
  55. output: {
  56. path: '/',
  57. filename: 'bundle.js',
  58. libraryTarget: 'commonjs2'
  59. },
  60. externals: [require.resolve('../../../dist/vue.runtime.common.js')],
  61. plugins: asBundle ? [new VueSSRServerPlugin()] : []
  62. })
  63. const bundle = asBundle
  64. ? JSON.parse(fs.readFileSync('/vue-ssr-server-bundle.json', 'utf-8'))
  65. : fs.readFileSync('/bundle.js', 'utf-8')
  66. return createBundleRenderer(bundle, options)
  67. }