mmf-fe / vite-plugin-cdn-import Goto Github PK
View Code? Open in Web Editor NEWImport modules from CDN with vite plugin
License: MIT License
Import modules from CDN with vite plugin
License: MIT License
{
name: 'codemirror',
var: 'codemirror',
alias: ['codemirror', '@codemirror/view', '@codemirror/lang-javascript', '@codemirror/lang-json', '@codemirror/theme-one-dark'],
path: [
'https://cdn.jsdelivr.net/npm/[email protected]/+esm',
'https://cdn.jsdelivr.net/npm/@codemirror/[email protected]/+esm',
'https://cdn.jsdelivr.net/npm/@codemirror/[email protected]/+esm',
'https://cdn.jsdelivr.net/npm/@codemirror/[email protected]/+esm',
'https://cdn.jsdelivr.net/npm/@codemirror/[email protected]/+esm']
}
以上写法浏览器报错:Uncaught SyntaxError: Cannot use import statement outside a module (at +esm:7:1)
另外建议示例能不能把所有方法都列举一下 全是简单使用的方法,不需要示例的给示例了。。。。
当我使用 rollup-plugin-external-globals 排除打包,并手动引入cdn链接时能够成功运行项目,但是使用vite-plugin-cdn-import打包项目时,浏览器会出现如下问题
vite.config.ts
import { defineConfig, type PluginOption } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
import { visualizer } from "rollup-plugin-visualizer";
// import externalGlobals from "rollup-plugin-external-globals";
import { Plugin as importToCDN } from "vite-plugin-cdn-import";
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: {
"@": resolve(__dirname, "src"),
},
},
plugins: [
react(),
visualizer() as PluginOption,
importToCDN({
modules: [
{
name: "react",
var: "React",
path: "https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js",
},
{
name: "react-dom",
var: "ReactDOM",
path: "https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js",
},
{
name: "dayjs",
var: "dayjs",
path: "https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.11/dayjs.min.js",
},
{
name: "antd",
var: "antd",
path: "https://cdnjs.cloudflare.com/ajax/libs/antd/5.17.4/antd.min.js",
},
],
}),
],
});
This plugin loads all scripts with <script src="${url}"></script>
. However this doesn't work for all packages.
Consider the following package: "nayuki-qr-code-generator": "1.8.0"
. When 'imported' in this way you get the following error:
Uncaught SyntaxError: export declarations may only appear at top level of a module
.
Could support for these types of packages be added?
Notes:
I've found I could get the desired result by manually adding the url source to the rollupOptions { rollupOptions: { external: ['https://unpkg.com/[email protected]/index.js'] } }
and modifying the import to:
// This imports the script from the cdn. Included in the build by adding it to rollupOptions.external.
// @ts-expect-error 2300 2307
import qrcodegen from 'https://unpkg.com/[email protected]/index.js';
// This part is marked as a type so it won't be included in the build but you can still use the type definitions.
// @ts-expect-error 2300
import type qrcodegen from 'nayuki-qr-code-generator';
index.ts 154行可以改一下
现在都加载到head里面了,一堆js文件,堵塞加载,失去了cdn的意义了
crypto-js
引入: import CryptoJS from "crypto-js"
用 vite 打包完后出现以下情况
vite: ^4.2.1
vite-plugin-cdn-import: ^0.3.5
但是手动换成以下就没问题
{
name: "crypto-js",
var: "CryptoJS",
path: "https://cdn.jsdelivr.net/npm/[email protected]/crypto-js.min.js"
},
Ts 的使用情况是如何的?
autoComplete 是自动完成cdn吗
path字段貌似是必须的且不能为空,但是这对纯css库并不友好。
plugins: [
vue(),
importToCDN({
modules: [
{
name: 'remixicon',
// path: '',
css: 'https://cdn.jsdelivr.net/npm/[email protected]/fonts/remixicon.css'
}
]
})
],
或许可以将他设置为可选字段?
@MMF-FE
[email protected] TypeError: importToCDN is not a function
我又来了,一起把这个插件变得更加完善把!
我在公司开发时。项目引用了很多包的css cdn,但是我启动的时候发现在开发环境下,css的cdn反而阻塞了渲染的速度,也就是说这个渲染速度没有本地加载css快。所以我觉得在开发环境下也引入cdn不太合适。
我想要达到的功能是: 我在main.js中引入css,然后开发环境下是用的是我本地引入的css。到了生产打包的时候,这个插件能够自动移除引入的css,并且在index.html中引入cdn的css。
当然这个插件目前已经达到了后者,现在只需要区分在生产打包时移除引入的css包就行了。
Why use rollup-plugin-external-globals in production and vite-plugin-externals in development? I'd appreciate it if you could answer my questions.
本来就是为了引入cdn减少包的体积的,为什么配置了之后还是把cdn的包也打包进来?
我现在的项目配置是
importToCDN({ modules:[ { name:'vue', var:'Vue', path: 'https://cache.hzjiace.com/js/[email protected]' } ] }),
但是这样的话在运行环境下是本地的路径
打包后才是正确的引入路劲
I download the vuetify.min.js from https://cdn.jsdelivr.net/
and save it into ./public/lib/vuetify.min.js in my project.
and I use importTOCDN like this:
plugins: [
importToCDN({
modules: [
{
name: 'vuetify',
var: 'Vuetify',
path: `lib/vuetify.min.js`
}
]
}),
...
But it return error:
Error: The configuration of module vuetify does not exist
``使用版本:"vite-plugin-cdn-import": "^1.0.1",
"unplugin-vue-components": "^0.24.1",
"vite": "^4.5.3",
"vue": "^3.2.47",
dev没有问题,build才有问题。
<script setup lang="ts">
// 以为使用了 unplugin-vue-components 会自动导入 el-card,所以这里没有 import
</script>
<template>
<el-card shadow="hover" header="(近十天)">
...
</el-card>
</template>
<style scoped lang="scss"></style>
左边图是编译后自动少了Element相关组件
unplugin-vue-components配置
Components({
resolvers: [
// 自动导入 Element Plus 组件
ElementPlusResolver(),
// 自动注册图标组件
IconsResolver(
// https://github.com/antfu/unplugin-icons#auto-importing
{
// {prefix}-{collection}-{icon}
// 默认前缀为 i,在 Element 图标前面加 IEp 加图标名 即可自动导入
// prefix: 'icon', // false 表示不用前缀
// 自动添加 @iconify-json/ep 包,ep 代表 ElementPlus
enabledCollections: ['ep'],
// 自动导入自定义的图标集合,默认前缀下,为 IMine 加图标文件名
customCollections: ['mine']
}
)
],
dts: path.resolve(pathSrc, 'typings', 'components.d.ts'),
dirs: [
// 指定组件所在位置,默认为 src/components
// 可以使用 glob 语法
'*/**/components'
]
})
vite-plugin-cdn-import 配置
import { Plugin as importToCDN } from 'vite-plugin-cdn-import'
export const cdnConfig = importToCDN({
prodUrl: 'https://unpkg.com/{name}@{version}/{path}',
modules: [
{
name: 'vue',
var: 'Vue',
path: 'dist/vue.global.prod.js'
},
{
name: 'vue-router',
var: 'VueRouter',
path: 'dist/vue-router.global.js'
},
{
name: 'vue-demi',
var: 'VueDemi',
path: 'lib/index.iife.js'
},
{
name: 'pinia',
var: 'Pinia',
path: 'dist/pinia.iife.js'
},
{
name: 'element-plus',
var: 'ElementPlus',
path: 'dist/index.full.min.js',
css: 'dist/index.css'
},
{
name: 'axios',
var: 'axios',
path: 'dist/axios.min.js'
},
{
name: 'dayjs',
var: 'dayjs',
path: 'dayjs.min.js'
},
{
name: 'echarts',
var: 'echarts',
path: 'dist/echarts.min.js'
}
]
})
vite build --mode production能生效
vite build --mode staging不能生效
您这边看看是不是应该要换个判断方式,或者在config配置插件时手动让开发者选择
或者是否有其他方式能满足方式二,因为打包也有测试环境或生产环境之分
建议将 version 作为 module 可选项
import { basicSetup } from 'codemirror'
import { EditorView } from "@codemirror/view"
import { javascript } from '@codemirror/lang-javascript'
import { json } from '@codemirror/lang-json'
import { oneDark } from '@codemirror/theme-one-dark'
I have an issue, that 1 deprecated subdependencies found: [email protected] in my project.
It turns out that this subdependencies is used by vite-plugin-cdn-import
devDependencies:
vite-plugin-cdn-import 1.0.1
└─┬ vite-plugin-externals 0.6.2
└─┬ magic-string 0.25.9
└── sourcemap-codec 1.4.8
What I can do about it ? Can you update the deprecated subdependencies?
hello 我在[email protected] [email protected] 使用vite-plugin-cdn-import 时遇到了问题
通过查看issues,找到原因是因为我使用了unplugin-auto-import, 有位小伙伴似乎找到了解决方法#13 (comment) 请问这个问题是否有解决的计划?
项目引入@vueuse/core库,它需要引入shared、core两个cdn才可以正常运行。
Attributes like crossorigin
and integrity
are very useful in regards of monitoring.
Also would like to have defer
or other custom attributes define on demand.
使用了unplugin-auto-import,在setup中省略了import,打包后就会提示错误
在浏览器中报错 ReactDOM.render 未定义。
vite-plugin-cdn-import/src/index.ts
Lines 154 to 156 in c37f095
cdn({
modules: [
{
name: 'react',
var: 'React',
path: `https://xxxx.com/react.production.min.js`,
},
],
}),
我就不能选择自己的js地址吗? 非要我按照你的格式要求使用吗? cdn厂商也必须按照你的格式要求提供包吗?
此外, 能否配置一些preloader defer async 之类的标签?
pnpm i vite-plugin-cdn-import --save-dev
WARN 1 deprecated subdependencies found: [email protected]
[email protected]
按照文档上配置报错,请问这是原因,找了很久都没有找到。
比如:
import * as PDFJS from 'pdfjs-dist/build/pdf.js'
externalGlobals 只把pdfjs-dist 当作key。并没有加入后面路径。
modulesConfig add:
"vue-router": {
var: "vue-router",
jsdeliver: {
path: "dist/vue-router.global.prod.js"
}
},
error: index.ts:18 Uncaught ReferenceError: vue is not defined at index.ts:18.
18: history: createWebHashHistory(),
I don't know why, can you fix it ?
Build failed in 9.67s
error during build:
RollupError: node_modules/react/cjs/react-jsx-runtime.production.min.js (12:7): "default" is not exported by "react?commonjs-external", imported by "node_modules/react/cjs/react-jsx-runtime.production.min.js".
file: G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/react/cjs/react-jsx-runtime.production.min.js:12:7
10: import * as commonjsHelpers from "commonjsHelpers.js";
11: import { __exports as reactJsxRuntime_production_min } from "\u0000G:/WorkSpace/WebStormProjects/react-learn-2024/day...
12: import require$$0 from "\u0000react?commonjs-external";
^
13:
14: 'use strict';var f=require$$0,k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnP...
at getRollupError (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/parseAst.js:394:41)
at error (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/parseAst.js:390:42)
at Module.error (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/node-entry.js:13896:16)
at Module.traceVariable (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/node-entry.js:14344:29)
at ModuleScope.findVariable (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/node-entry.js:12025:39)
at Identifier.bind (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/node-entry.js:7382:40)
at VariableDeclarator.bind (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/node-entry.js:4776:23)
at VariableDeclaration.bind (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/node-entry.js:4772:28)
at Program.bind (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/node-entry.js:4772:28)
at Module.bindReferences (file:///G:/WorkSpace/WebStormProjects/react-learn-2024/day-06/rt-jk/node_modules/rollup/dist/es/shared/node-entry.js:13877:18)
`
类似这个 injectTo?: 'head' | 'body' | 'head-prepend' | 'body-prepend'
,
默认script
插入到body
,link
插入到head
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
build.rollupOptions.external
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.