index.js
async function getComponent () { const { default: _ } = await import(/*webpackChunkName: "lodash"*/'lodash') await import(/* webpackChunkName: "style" */ './style.css') const element = document.createElement('div') element.innerHTML = _.join(['Hello', 'webpack'], ' ') const br = document.createElement('br') const btn = document.createElement('button') btn.innerHTML = 'Click me and look at the console' btn.onclick = e => import(/*webpackChunkName: "print" */ "./print").then(({ default: print }) => { print() }) element.appendChild(br) element.appendChild(btn) return element } getComponent().then(component => { document.body.appendChild(component) })
print.js
console.log('Print module loaded!') export default () => { console.log('Button clicked!') }
webpack.common.js
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const { CleanWebpackPlugin } = require('clean-webpack-plugin') const PreloadWebpackPlugin = require('@vue/preload-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') module.exports = { entry: { index: './src/index.js', }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] } ] }, plugins: [ new HtmlWebpackPlugin(), new CleanWebpackPlugin(), new PreloadWebpackPlugin(), new MiniCssExtractPlugin() ] }
preload和prefetch的多页面配置
假设存在四个页面: index.html, book.html, content.html. search.html
new HtmlWebpackPlugin({ title: 'index', template: './src/pages/index/index.html', filename: 'index.html', chunks: ['index'] // 标识页面chunk }), new HtmlWebpackPlugin({ title: 'book', template: './src/pages/book/book.html', filename: 'book.html', chunks: ['book'] }), new HtmlWebpackPlugin({ title: 'content', template: './src/pages/content/content.html', filename: 'content.html', chunks: ['content'] }), new HtmlWebpackPlugin({ title: 'search', template: './src/pages/search/search.html', filename: 'search.html', chunks: ['search'] }), new PreloadWebpackPlugin({ rel: 'preload', excludeHtmlNames: ['book.html', 'content.html', 'search.html'], include: ['index'] // index preload本页面的 }), new PreloadWebpackPlugin({ rel: 'prefetch', excludeHtmlNames: ['book.html', 'content.html', 'search.html'], include: ['book'] // book prefetch index页面 }), new PreloadWebpackPlugin({ rel: 'preload', excludeHtmlNames: ['index.html', 'content.html', 'search.html'], include: ['book'] // book preload 本页面 }), new PreloadWebpackPlugin({ rel: 'prefetch', excludeHtmlNames: ['index.html', 'content.html', 'search.html'], include: ['content'] // content prefetch book 页面 }), new PreloadWebpackPlugin({ rel: 'preload', excludeHtmlNames: ['index.html', 'book.html', 'search.html'], include: ['content'] // content preload 本页面 }), new PreloadWebpackPlugin({ rel: 'preload', excludeHtmlNames: ['index.html', 'book.html', 'content.html'], include: ['search'] // search preload 本页面 })