Rollup 打包模块化代码以及第三方依赖
以下是一个完整的项目示例,展示如何使用 Rollup 打包模块化代码以及第三方依赖。
首先,你需要创建一个项目目录,并在该目录下执行以下步骤:
初始化项目:
打开终端,并在项目目录下运行以下命令以初始化一个新的 npm 项目:
1
npm init -y
安装 Rollup 及相关插件:
安装 Rollup、@rollup/plugin-node-resolve 和 @rollup/plugin-commonjs 插件:
1
npm install rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs --save-dev
创建项目文件结构:
创建以下文件和目录结构:
1
2
3
4
5
6
7
8project-root/
├── src/
│ ├── index.js
│ ├── module1.js
│ └── module2.js
├── dist/
├── rollup.config.js
└── package.json编写代码和配置文件:
编写模块化代码和 Rollup 配置文件。
src/index.js:
1
2
3
4
5
6
7
8
9import { add } from './module1.js';
import { subtract } from './module2.js';
import externalLibrary from 'your-external-library';
const result = add(5, 3);
const difference = subtract(10, 4);
const externalResult = externalLibrary.someFunction();
console.log(result, difference, externalResult);src/module1.js:
1
2
3export function add(a, b) {
return a + b;
}src/module2.js:
1
2
3export function subtract(a, b) {
return a - b;
}rollup.config.js:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import { terser } from 'rollup-plugin-terser';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [
resolve(),
commonjs(),
terser()
]
};
运行 Rollup:
在终端中运行 Rollup 命令,将你的代码和第三方依赖打包成一个独立的 JavaScript 文件:
1
npx rollup -c
在 HTML 文件中引入打包后的文件:
创建一个 HTML 文件并在其中引入打包后的 JavaScript 文件:
1
2
3
4
5
6
7
8
9
<html>
<head>
<title>Rollup Example</title>
</head>
<body>
<script src="dist/bundle.js"></script>
</body>
</html>运行项目:
在浏览器中打开你的 HTML 文件,查看控制台输出。
这样,你就创建了一个完整的项目示例,演示了如何使用 Rollup 打包模块化的代码以及第三方依赖,然后在浏览器中运行它们。确保你的项目中的 your-external-library
替换为实际的第三方依赖,并根据需要进行适当的配置和修改。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 寻屿!