1.0.5 • Published 1 year ago
script-load-webpack-plugin v1.0.5
简介
基于 @vuejs/preload-webpack-plugin 实现的插件, 实现了资源的预加载。
主要区别在于:
- 专注于脚本(script)。
- 引入了 webpack 5 的一些特性。
<link href="src_async_js.f23b5bce.js" rel="preload" as="script"></link>
<link href="src_async_js.f23b5bce.js" rel="prefetch"></link>
预检查
确保 webpack 的版本在 5 以上, 并且正在使用 html-webpack-plugin。
安装
通过 npm 安装, 并将其添加到开发时依赖中 devDependencies
:
npm install script-load-webpack-plugin --save-dev
或者
通过 yarn 安装:
yarn add script-load-webpack-plugin --dev
选项
下面是 script-load-webpack-plugin
的配置项:
字段名 | 类型 | 默认值 | 描述 |
---|---|---|---|
rel | {String} | preload | 脚本的预加载模式 |
include | {String\|Object} | asyncChunks | 指定需要预加载的脚本 |
案例
下面是 webpack 的配置的案例。
使用 preload 预加载异步文件
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ScriptLoadWebpackPlugin } = require('script-load-webpack-plugin');
module.exports = {
//...
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html',
chunks: ['index'],
inject: 'body'
}),
new ScriptLoadWebpackPlugin({
rel: 'preload',
include: 'asyncChunks'
})
]
//...
}
使用 prefetch 加载异步文件
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ScriptLoadWebpackPlugin } = require('script-load-webpack-plugin');
module.exports = {
//...
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html',
chunks: ['index'],
inject: 'body'
}),
new ScriptLoadWebpackPlugin({
rel: 'preload',
include: 'asyncChunks'
})
]
//...
}
指定 chunk
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ScriptLoadWebpackPlugin } = require('script-load-webpack-plugin');
module.exports = {
//...
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html',
chunks: ['index'],
inject: 'body'
}),
new HtmlWebpackPlugin({
template: './public/index2.html',
filename: 'index2.html',
chunks: ['index2'],
inject: 'body'
}),
new ScriptLoadWebpackPlugin({
rel: 'preload',
include: {
chunks: ['index']
}
})
]
//...
}
指定 entry
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ScriptLoadWebpackPlugin } = require('script-load-webpack-plugin');
module.exports = {
//...
entry: {
index: './src/index.js',
index2: './src/index2.js'
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
filename: 'index.html',
chunks: ['index'],
inject: 'body'
}),
new HtmlWebpackPlugin({
template: './public/index2.html',
filename: 'index2.html',
chunks: ['index2'],
inject: 'body'
}),
new ScriptLoadWebpackPlugin({
rel: 'preload',
include: {
entries: ['index2']
}
})
]
//...
}