Rollup从入门到入坑(2)引入第三方库

到目前为止,我们已经可以使用Rollup编译本地代码,但有些时候,借助社区的力量可以使我们的程序编写更高效。
ms为例

引入第三方模块

npm i -s ms

修改src/index.js

// src/index.js
import ms from 'ms';

export default function hourToSeconds(hours) {
    return ms(`${hours}h`);
}

非常简单的导出一个方法,用于将小时转换为秒。
此时的rollup.config.js

// rollup.config.js
export default {
    input: 'src/index.js',
    output: {
      file: 'dist/bundle.js',
      format: 'cjs'
    }
  };

当运行npm run build,显示以下错误。
Unresolved dependencies
提示 Unresolved dependencies
https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
打开链接
external dependency
大意是 Rollup 默认只解析相对路径的模块,对于以绝对路径引入的模块,不会作为bundle的一部分引入,这种模块会作为运行时的外部依赖,如果你就是想这样,你可以将模块id写入external数组。
如果你不想让你的模块运行时依赖这种第三方引入的模块,你需要让Rollup找到并将其一并打包到bundle中 可以使用@rollup/plugin-node-resolve
对于一些在node.js模块,如果想要运行在浏览器端 可能会需要 rollup-plugin-node-polyfills
直接引入该模块

npm i -D @rollup/plugin-node-resolve

同时修改rollup配置文件

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';

export default {
    input: 'src/index.js',
    output: {
      file: 'dist/bundle.js',
      format: 'cjs',
      // name: 'howlong'
    },
    plugins: [
      resolve()
    ]
  };

再次build,又报错,还是个Error,好像问题更大了。
no default
点击链接
plugin-common
原因是ms模块没有默认的导出声明,可以使用@rollup/plugin-commonjs来尝试解决此类问题,但因为CommonJS的自由性,可能会需要手动配置。ms这个库由于是官方demo中的一个简单的第三方库,所以不需要任何额外的配置,只需引入@rollup/plugin-commonjs即可。
安装插件

npm i -D @rollup/plugin-commonjs

编辑配置文件

// rollup.config.js
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: 'cjs',
  },
  plugins: [
    resolve(),
    commonjs()
  ]
};

再次 npm run build,可以看到编译通过,并且将ms的代码也打包进了我们的模块文件。

本节,我们引入了第三方的库函数,通过Rollup的报错信息的引导引入了两个插件,对Rollup插件有了基本的认识。

参考

rollup-starter-lib

猜你喜欢

转载自blog.csdn.net/u010464354/article/details/104783306