面试题答案
一键面试- 安装
@vue - cli - service - plugin - cdn
:- 打开终端,进入项目根目录,运行以下命令:
npm install @vue - cli - service - plugin - cdn --save - dev
- 配置
vue.config.js
:- 在项目根目录创建或编辑
vue.config.js
文件。 - 在
vue.config.js
中添加如下内容:
const cdn = { // 开发环境下的CDN链接 dev: { css: [], js: [] }, // 生产环境下的CDN链接 prod: { css: [ // 例如element - ui的CSS链接 'https://unpkg.com/element - ui/lib/theme - chalk/index.css' ], js: [ // 例如Vue的CDN链接 'https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js', // 例如element - ui的JS链接 'https://unpkg.com/element - ui/lib/index.js' ] } }; module.exports = { configureWebpack: config => { if (process.env.NODE_ENV === 'production') { config.externals = { // 配置外部依赖,以避免打包进bundle 'vue': 'Vue', 'element - ui': 'ELEMENT' }; } }, chainWebpack: config => { config.plugin('html').tap(args => { if (process.env.NODE_ENV === 'production') { args[0].cdn = cdn.prod; } else { args[0].cdn = cdn.dev; } return args; }); } };
- 在项目根目录创建或编辑
- 在模板中使用CDN资源:
- 在
public/index.html
模板文件中,通过htmlWebpackPlugin.options.cdn
来注入CDN资源。例如:
<!DOCTYPE html> <html lang="zh - CN"> <head> <meta charset="utf - 8"> <meta http - equiv="X - UA - Compatible" content="IE=edge"> <meta name="viewport" content="width=device - width,initial - scale = 1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title><%= htmlWebpackPlugin.options.title %></title> <!-- 注入CSS资源 --> <% for (var i in htmlWebpackPlugin.options.cdn.css) { %> <link href="<%= htmlWebpackPlugin.options.cdn.css[i] %>" rel="stylesheet"> <% } %> </head> <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> <!-- 注入JS资源 --> <% for (var i in htmlWebpackPlugin.options.cdn.js) { %> <script src="<%= htmlWebpackPlugin.options.cdn.js[i] %>"></script> <% } %> </body> </html>
- 在
- 处理相关依赖:
- 在
main.js
等入口文件中,对于通过CDN引入的库,不再使用import
导入。例如,如果使用了Vue和Element - UI:
// 不需要 import Vue from 'vue'; // 不需要 import ElementUI from 'element - ui'; // 不需要 import 'element - ui/lib/theme - chalk/index.css'; // 直接使用全局变量 // 创建Vue实例 new Vue({ el: '#app', components: { App }, template: '<App/>' });
- 这样,通过CDN引入的库不会被打包进项目的
bundle.js
文件中,从而减小了打包体积,提升了项目在生产环境下的加载速度。
- 在