零配置无痛构建Javascript的库/组件
发布于 6 年前 作者 axetroy 3152 次浏览 来自 分享

WHY

对于经常造轮子的人来说,最痛苦的事莫过于配置开发环境。

如果你构建一个纯粹的库,你可能需要ES6支持,那么你需要Babel,还需要安装Babel,然后根据需要的特性安装preset,安装plugins

如果你需要构建一个React/Vue组件,那么就不是Babel那么简单,还需要配置Webpack。

包括一堆的Loader,plugins,entry,output,devServer等等,不厌其烦…

所以很迫切的需要一个零配置的开发工具,你看parcel不就是因为零配置备受推崇吗。

所以,自己撸一个工具,configless是目标,专注于打包库/组件.

npm install @axetroy/libpack -g

构建一个Vue组件

// index.vue
<template>
  <div>
    <h2>Hello world</h2>
    <h2>This is an Vue example component</h2>
  </div>
</template>

<script>
console.log("Load component");
export default {
  name: "index"
};
</script>

<style scoped>

</style>
# -- externals 指明vue需要外部加载
libpack ./index.vue ./build --externals vue

然后你还可以预览一下刚写的组件

// main.js
import Vue from "vue";
import App from "./index.vue";

new Vue({
  el: document.body,
  render: h => h(App)
});
libpack ./main.js ./build --server

完整代码

构建一个React组件

// index.jsx
import React, { Component } from "react";

class Example extends Component {
  render() {
    return (
      <div>
        <h2>Hello world</h2>
        <h3>This is an react example component</h3>
      </div>
    );
  }
}

export default Example;
# -- externals 指明react和react-dom需要外部加载
libpack ./index.jsx ./build --watch --externals react,react-dom

然后你还可以预览一下刚写的组件

libpack ./app.jsx ./build --server

完整代码

Typescript

// src/index.ts
class Person {
  say(word: string) {
    console.log("hello " + word);
  }
}

new Person().say("world");

libpack ./src/index.ts ./build

typescript项目需要有tsconfig.json,如果项目目录不存在,那么会创建一个默认配置

完整代码

Flow

// index.js
// @flow
class Person {
  say(word: string) {
    console.log("hello " + word);
  }
}

new Person().say("world");

libpack ./index.js ./build

完整代码

Javascript

// index.js
console.log("Hello world");

// generator
function* generator() {
  yield Promise.resolve();
}

// async await
async function asyncFunction() {
  await Promise.resolve();
}

// dynamic import
import("./antoher");

// do expression
function doExpression() {
  let a = do {
    if (x > 10) {
      ("big");
    } else {
      ("small");
    }
  };
}

// Object rest spread
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }

// decorator
function readable() {
  return function() {};
}

@readable()
class Stream {}
libpack ./index.js ./build

完整代码

最后

libpack仅仅是一个内置了多个preset和plugins的Webpack配置,省去了配置的烦恼。

你也不需要关心怎么配置es2015,es2016,es2017,也不用关心你能不能用新特性.

撸起袖子就是干.

欢迎各位大佬指教

Github: https://github.com/axetroy/libpack

2 回复

既然是库/组件的开发用的,lz不考虑用rollup吗?

@steambap 因为不是单纯的打包JS,所以我觉得webpack更合适一些。

来自酷炫的 CNodeMD

回到顶部