相关文章推荐
博学的绿茶  ·  使用Resource Hacker ...·  2 月前    · 
博学的绿茶  ·  Utility Types | Vue.js·  10 月前    · 
博学的绿茶  ·  Help And Training ...·  11 月前    · 
博学的绿茶  ·  r - Caused by error ...·  1 年前    · 
独立的眼镜  ·  如何连接Babelfish for RDS ...·  1小时前    · 
发财的蛋挞  ·  Microsoft Azure Data ...·  1小时前    · 
冷冷的投影仪  ·  Secure an ASP.NET ...·  1小时前    · 
不羁的生姜  ·  PSPSDK 开发的时候出现 ...·  1小时前    · 
儒雅的投影仪  ·  Perl 包和模块 | ·  3 小时前    · 

使用 npm 初始化项目,然后安装 webpack webpack-cli lodash

npm init -y
npm install --save-dev webpack webpack-cli

src/index.js

export const add = (x, y) => x + y;
export const subtract = (x, y) => x - y;

webpack.config.js

const path = require('path');
module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'myMath.js',

在上面的例子中,我们将通知 webpack 将 src/index.js 打包到 dist/myMath.js 中。

导出 library

到目前为止,一切都应该与打包应用程序一样,这里是不同的部分 - 我们需要通过 output.library 配置项暴露从入口导出的内容。

webpack.config.js

  const path = require('path');
  module.exports = {
    mode: 'production',
    entry: './src/index.js',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'myMath.js',
+     library: "myMath",

我们导出了 myMath以便用户可以通过脚本标签使用它:

test/index.html

<script src="../dist/myMath.js"></script>
<script>
  myMath.add(1, 2);
</script>

然而它只能通过被脚本标签引用而发挥作用,它不能运行在 CommonJSAMDNode.jsES module 等环境中。

输出 ES 模块

该特性仍然是实验性的,并且没有完全支持,所以请确保事先启用 experiments.outputModule。除此之外,你可以在 这里 追踪开发进度。

const path = require('path');
module.exports = {
  mode: 'production',
  entry: './src/index.js',
  experiments: {
    outputModule: true,
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'myMath.js',
    library: {
      // name: 'myMath', // 这里不要执行 name
      type: 'module',

执行 npx webpack

test/index.html

<script type="module">
  import { add } from '../dist/myMath.js'
  console.log(add(1, 2));
</script>

可以看到能正常输出

输出 umd

一个库作者,我们希望它能够以不同的环境,方式,用户应该能够通过以下使用打包后的库:

 
推荐文章