如何使用 webpack 和 babel 将 js 文件编译为库

How to compile a js file as library using webpack and babel

您好,我如何使用 webpack 将单个 js class 文件编译为库以生成可包含在脚本标记中的输出

<script src='demo/demo.js'></script>

还有一个可以导入的输出

import demo from 'demo'

如果想在AMD、CommonJS、Nodejs等不同环境下使用demo库。您需要使用 output.library 选项并将其类型设置为 'umd'.

此外,我们需要将output.globalObject选项设置为'this'

When targeting a library, especially the libraryTarget is 'umd', this option indicates what global object will be used to mount the library. To make UMD build available on both browsers and Node.js, set output.globalObject option to 'this'.

一个例子:

demo/src/demo.js:

export class Demo {
  sayHello() {
    console.log("hello!");
  }
}

demo/webpack.config.js:

const path = require("path");

module.exports = {
  entry: "./src/demo.js",
  output: {
    path: path.resolve(__dirname, "lib"),
    filename: "demo.js",
    library: {
      name: "demo",
      type: "umd",
    },
    globalObject: "this",
  },
  mode: "development",
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
  },
};

demo/package.json:

{
  "name": "demo",
  "version": "1.0.0",
  "main": "lib/demo.js",
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "babel-loader": "^8.2.2",
    "webpack": "^5.51.1",
    "webpack-cli": "^4.8.0"
  }
}

消费端

通过script标签在浏览器中使用demo库:

index.html:

<!DOCTYPE html>
<html lang="en">

<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">
  <title>Document</title>
</head>

<body>
  <script src='./demo/lib/demo.js'></script>
  <script>
    window.onload = () => {
      const { Demo } = window.demo;
      const demo = new Demo()
      demo.sayHello();
    }
  </script>
</body>

</html>

通过 ES6 import 语法在 index.js 文件中使用 demo

index.js:

import { Demo } from "./demo/lib/demo";

const d = new Demo();
d.sayHello();

消费方webpack.config.js:

const path = require("path");

module.exports = {
  entry: "./index.js",
  output: {
    path: path.resolve(__dirname),
    filename: "index-bundled.js",
  },
  mode: "development",
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"],
          },
        },
      },
    ],
  },
};

生成index-bundled.js文件后,运行node index-bundled.js。输出:

⚡  node index-bundled.js 
hello!