ES实战

41 阅读1分钟

node 端,有一个 http 的模块,(基于 net 的模块 ( eventEmitter / stream 的模块 ));

rollup 的使用 和 装饰器实现API前缀

1: 使用 rollup 一般是 自己写插件用的,webpack 什么都能干,但是配置麻烦。 对 esm 打包, 构建 bundle。

rollup 一般是 自己写插件用的,webpack 什么都能干,但是配置麻烦。

在node 中使用 esm

  • type: 'module'
  • .mjs 使用mjs文件
  • rollup
  • .....
需要的包
@babel/plugin-proposal-decorators
@babel/plugin-proposal-class-properties
@babel/preset-env
@babel/plugin-proposal-decorators
@babel/core @babel/preset-env
yarn add rollup rollup-plugin-babel -D

配置文件

配置 rollup.config.js 文件

可以看到,这个配置文件比 webpack 少很多

import babel from 'rollup-plugin-babel';

export default { 
    input: './src/index.js', 
    output: { 
        file: './dist/bundle.js', 
        format: "umd", 
    }, 
    treeshake: false, 
    plugins: [ 
        babel({ 
            runtimeHelpers: true, 
            extensions: [".js", ".ts"], 
            exclude: "node_modules/**", 
            externalHelpers: true, 
        }),
    ],
};

配置 .babelrc 文件

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "modules": false,
                "loose": true,
                "targets": "node 16",
                "useBuiltIns": "usage",
                "corejs": {
                    "version": "3.22",
                    "proposals": true
                }
            }
        ]
    ],
    "plugins": [
        [
            "@babel/plugin-proposal-decorators",
            {
                "legacy": true
            }
        ],
        [
            "@babel/plugin-proposal-class-properties",
            {
                "loose": true
            }
        ]
    ]
}

为了方便还有能运行打包后的文件,在 package.json 添加命令

-c -w // -c: rollup.config.js 文件, -w: watch

"scripts" {
 "dev": "rollup -c -w",
 "nodemon": "nodemon ./dist/bundle.js"
}

执行 npm run dev 打包文件, 可以在 rollup.config.js 开启树摇等 命令,把没用到的代码 摇掉。 再用 npm run nodemon 执行 打包的文件。

2: 装饰器做前缀

这个要项目,代码较多,不发了