Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
使用 Rollup 创建具有 CommonJS 和 ESM 支持的 NPM 包_创想鸟

使用 Rollup 创建具有 CommonJS 和 ESM 支持的 NPM 包

使用 rollup 创建具有 commonjs 和 esm 支持的 npm 包

使用 rollup 创建具有 commonjs (cjs) 和 ecmascript 模块 (esm) 支持的 npm 包

在这篇文章中,我们将探索如何使用 rollup 创建支持 commonjs (cjs) 和 ecmascript 模块 (esm) 的 npm 包。

rollup 是一个 javascript 捆绑器,非常适合创建库和包,因为它生成高度优化的代码包,可以在不同环境中轻松使用。

项目结构:

my-npm-package/├── src/│   └── index.js├── rollup.config.js└── package.json

1. 配置项目

首先为您的 npm 包创建一个新目录。在目录中,运行命令:

npm init -y

这将生成一个基本的 package.json 文件。

然后安装必要的依赖项:

npm install rollup rollup-plugin-commonjs rollup-plugin-node-resolve

解释依赖关系:

rollup:模块打包工具。rollup-plugin-commonjs: 用于处理 commonjs 模块的 rollup 插件。rollup-plugin-node-resolve: 用于解决 node.js 模块依赖关系的 rollup 插件。

2.创建src文件夹

在项目目录中创建一个名为 src 的文件夹。

在 src 中,使用 npm 包中的代码创建一个 index.js 文件。

// src/index.jsfunction hello(name) {  return `hello, ${name}!`;}export { hello };

3. 创建 rollup.config.js 文件

使用 rollup 配置创建 rollup.config.js 文件。

rollup 有 2 个输出配置选项:第一个:所有代码都在一个输出文件中。第二个:使用preservemodules来维护模块结构。

3.1 rollup.config.js 文件,不保留模块结构

rollup 默认情况下将所有模块合并到一个输出文件中。这意味着您的所有模块(包括您自己的模块及其依赖项)都将合并到一个 javascript 文件中。

//rollup.config.jsimport commonjs from 'rollup-plugin-commonjs';import resolve from 'rollup-plugin-node-resolve';export default [  {    input: 'src/index.js', // arquivo principal de entrada    output: {      file: 'dist/index.cjs.js', // diretório de saída para commonjs      format: 'cjs',      sourcemap: true,    },    plugins: [      resolve(),      commonjs(),    ],  },  {    input: 'src/index.js', // arquivo principal de entrada    output: {      file: 'dist/index.esm.js', // diretório de saída para es modules      format: 'esm',      sourcemap: true,    },    plugins: [      resolve(),  // resolve módulos de node_modules      commonjs()  // converte pacotes commonjs para esmodules    ],  },];

解释设置:

input: 定义 rollup 的输入文件。output: 设置输出文件和输出格式。format: 定义模块格式(esm 或 commonjs)。plugins: 定义将在 rollup 中使用的插件。

3.2 rollup.config.js 文件保留模块结构

rollup 保留了原始代码的模块结构。项目中的每个模块都将打包在自己的文件中。

import resolve from '@rollup/plugin-node-resolve';import commonjs from '@rollup/plugin-commonjs';export default {  input: 'src/index.js',  // arquivo principal de entrada  output: [    {      dir: 'dist/cjs', // diretório de saída para commonjs      format: 'cjs',      entryfilenames: '[name].js', // mantém o nome do arquivo original      exports: 'auto',      preservemodules: true, // preserva a estrutura dos módulos      preservemodulesroot: 'src', // diretório base que será mantido    },    {      dir: 'dist/esm', // diretório de saída para es modules      format: 'esm',      entryfilenames: '[name].js',      preservemodules: true,      preservemodulesroot: 'src',    }  ],  plugins: [    resolve(),  // resolve módulos de node_modules    commonjs()  // converte pacotes commonjs para esmodules  ]};

解释设置:

entryfilenames: 使用占位符定义输出文件名的模式:[name]: 替换为模块名称。[hash]:替换为文件的唯一哈希值。[format]: 替换为模块格式(esm 或 cjs)。preservemodules: 保留代码的原始模块结构。如果为 true,每个模块将打包在自己的文件中。preservemodulesroot: 定义要保留的模块的根目录。

4.配置package.json

使用以下信息更新 package.json 文件:

{  "name": "my-npm-package",  "version": "1.0.0",  "description": "",  "main": "dist/index.cjs.js",  "module": "dist/index.esm.js",  "scripts": {    "build": "rollup -c",    "dev": "rollup -c --watch"  },  "repository": {    "type": "git",    "url": "git+https://github.com/your-username/my-npm-package.git"  },  "author": "",  "license": "mit",  "devdependencies": {    "rollup": "^3.2.1",    "rollup-plugin-commonjs": "^18.0.0",    "rollup-plugin-node-resolve": "^6.3.0"  }}

解释属性:

名称: npm 包名称。版本:套餐版本。描述:包装描述。main: 定义 commonjs 项目的主文件。模块: 定义 esm 项目的主文件。脚本: 定义用于构建和开发的脚本。repository: 定义包存储库。作者: 包作者姓名。许可证: 软件包许可证。

5. 编译并发布包

运行 npm install 命令来安装依赖项。

运行 npm run build 命令来编译您的包。这将在 dist/.

中生成编译后的文件

然后使用 npmpublish 命令将包发布到 npm。

6. 使用包

您现在可以在其他项目中使用您创建的 npm 包。

commonjs 项目中的示例:

const mypackage = require('my-npm-package');console.log(mypackage.hello('world'));

esm 项目中的示例(当 package.json 具有 “type”: “module” 时):

import { hello } from 'my-npm-package';console.log(hello('World'));

结论

使用 rollup 创建具有 commonjs 和 esm 支持的 npm 包非常简单。通过遵循本文中概述的步骤,您可以构建一个灵活的、可重用的包,以满足不同项目的需求。

以上就是使用 Rollup 创建具有 CommonJS 和 ESM 支持的 NPM 包的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1493236.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
SQL 序列 ||作者:Munisekhar Udavalapati || MySQL || SQL
上一篇 2025年12月19日 15:31:21
Shadcn CLI如何使用错误常量来提高代码可读性
下一篇 2025年12月19日 15:31:36

相关推荐

发表回复

登录后才能评论
关注微信