⚙️

viteでNode.js用のpackage作る時の設定

2023/12/03に公開

esbuild使うことにしたので供養

package.json
{
  "name": "vite-node-package-example",
  "version": "0.0.0",
  "scripts": {
    "build": "vite build && tsc"
  },
  "devDependencies": {
    "@types/node": "^20.10.2",
    "camelcase": "^8.0.0",
    "typescript": "^5.2.2",
    "vite": "^5.0.0"
  },
  "type": "module",
  "main": "./dist/index.cjs",
  "module": "./dist/index.js",
  "files": [
    "dist"
  ],
  "exports": {
    ".": {
      "require": "./dist/index.cjs",
      "import": "./dist/index.js"
    }
  }
}
vite.config.js
import { resolve } from "path";
import { defineConfig } from "vite";
import { name } from "./package.json";
import camelCase from "camelcase";

const IGNORE_ROLLUP_WARNING_CODE = [
  "MISSING_GLOBAL_NAME",
  "MISSING_NODE_BUILTINS",
];

export default defineConfig({
  build: {
    lib: {
      entry: resolve(__dirname, "src/index.ts"),
      name: camelCase(name, { pascalCase: true }),
    },
    ssr: true,
    rollupOptions: {
      onwarn: (warning, defaultHandler) => {
        if (IGNORE_ROLLUP_WARNING_CODE.includes(warning.code)) return;
        defaultHandler(warning);
      },
    },
  },
});
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "emitDeclarationOnly": true,
    "declaration": true,
    "declarationDir": "./dist",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src"]
}

Discussion