使用 IIFE 创建独立的 Web 组件构建

Creating a standalone web component build using as an IIFE

我已经创建了一个 Web 组件,用于在任何 html 内容中显示要点。

我使用 Lit Element Typescript Starter Project 作为基准,它带有一个 rollup.config.js 文件。

我将输出格式更改为 iife,其余部分保持不变,但组件和包名称除外。我这样做的原因是我希望可以通过脚本标签轻松访问捆绑包,并且汇总说 iife 格式可以做到这一点。

This is the modified rollup.config.js file.

// ============================================
// The configuration is based on the rollup starter
// app found here:
//
// https://github.com/rollup/rollup-starter-app/blob/master/package.json
//
// This project is based
// ============================================


/**
 * @license
 * Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at
 * http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at
 * http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at
 * http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at
 * http://polymer.github.io/PATENTS.txt
 */

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import {terser} from 'rollup-plugin-terser';
import replace from '@rollup/plugin-replace';
import filesize from 'rollup-plugin-filesize';

// `npm run build` -> `production` is true
// `npm run dev` -> `production` is false
const production = !process.env.ROLLUP_WATCH;

export default {
  input: 'fs-gist.js',
  output: {
    file: 'fs-gist.bundle.js',
    format: 'iife', // immediately-invoked function expression — suitable for <script> tags
    sourcemap: true,
  },
  onwarn(warning) {
    if (warning.code !== 'THIS_IS_UNDEFINED') {
      console.error(`(!) ${warning.message}`);
    }
  },
  plugins: [
    replace({'Reflect.decorate': 'undefined'}),
    resolve(), // tells Rollup how to find date-fns in node_modules
    commonjs(), // converts date-fns to ES modules
    production && terser({
        module: true,
        warnings: true,
        mangle: {
          properties: {
            regex: /^__/,
          },
        },
      }),
      filesize({
        showBrotliSize: true,
      })
  ],
};

构建似乎运行良好。这里有一个演示:

https://stackblitz.com/edit/typescript-fs-gist?file=index.ts

很好奇是否有人知道自从我将格式从 esm 更改为 iife 后是否应该调整或更改任何其他汇总设置?

汇总配置实际上取决于您想要做什么。如果它当前适用于您想要做的事情,那就太好了,无需更改任何内容。

因为它是一个配置文件,如果它不起作用,其他一切都取决于您以及您想要从中得到什么。例如,如果你想让它在旧的浏览器上工作,你可以使用插件 @rollup/plugin-babel 来转换你的代码。如果您想将它作为 umd 和 es 提供,您可以将它们添加到构建步骤中。

汇总文档非常详尽,您应该查看可能的内容:https://rollupjs.org/guide/en/

一旦您对项目的需求有了更好的了解,就可以在文档中搜索有关如何添加特定插件、步骤等的示例。