首页 > 解决方案 > Rollup 将 Vue 项目嵌入到纯 HTML 中

问题描述

我有一个 Vue 应用程序,我使用汇总作为捆绑程序。我想要做的是能够将捆绑的min.js文件导入任何 html 站点,因此可以轻松嵌入应用程序。我已经在 npm 上有了它,但我希望没有 Node 的人能够嵌入它。

我的包适用于 NPM,但是当我尝试将包直接导入到 html 时,我收到一个错误axios is not defined,但是当我尝试在节点包中捆绑时,node-resolve 我收到此错误:[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)甚至没有创建包。

这是正确的方法还是有更好的方法来做到这一点?谢谢

我的文件结构是这样的:

build
--rollup.config.js
dist
--player.min.js
--player.umd.js
--player.esm.js
node_modules
--<all_packages>
src
--<several .Vue components>
--Player.vue (Main file)
--wrapper.js (Wraps project and exports the player)

rollup.config.js:

import commonjs from '@rollup/plugin-commonjs'; // Convert CommonJS modules to ES6
import vue from 'rollup-plugin-vue'; // Handle .vue SFC files
import buble from '@rollup/plugin-buble'; // Transpile/polyfill with reasonable browser support
import replace from '@rollup/plugin-replace';
import image from '@rollup/plugin-image';
import 'dotenv/config';

export default {
    input: 'src/wrapper.js', // Path relative to package.json
    output: {
        name: 'Player',
        exports: 'named',
    },
    plugins: [
        replace({
          'process.env.VUE_APP_ENV': JSON.stringify(process.env.VUE_APP_ENV),
          'process.env.VUE_APP_ROOT_API': JSON.stringify(process.env.VUE_APP_ROOT_API)
        }),
        commonjs(),
        vue({
            css: true, // Dynamically inject css as a <style> tag
            compileTemplate: true, // Explicitly convert template to render function
        }),
        buble({
          transforms: {
            forOf: false
          }
        }), // Transpile to ES5
        image()
    ],
};

Wrapper.js 看起来像这样:

// Import vue component
import player from './Player.vue'

// Declare install function executed by Vue.use()
export function install (Vue) {
  if (install.installed) return
  install.installed = true
  Vue.component('Player', player)
}

// Create module definition for Vue.use()
const plugin = {
  install
}

// Auto-install when vue is found (eg. in browser via <script> tag)

let GlobalVue = null
if (typeof window !== 'undefined') {
  GlobalVue = window.Vue
} else if (typeof global !== 'undefined') {
  GlobalVue = global.Vue
}
if (GlobalVue) {
  GlobalVue.use(plugin)
}

// To allow use as module (npm/webpack/etc.) export component
export default player

标签: vue.jsrollup

解决方案


推荐阅读