UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Figma】FigmaプラグインをWebpackをつかってバンドルする仕組みをつくる

前回Figmaプラグインについて調べた

uga-box.hatenablog.com

このときはテンプレートをダウンロードしたときの実装済みの挙動を確認しただけだったが、今度はもう少し自分で書いてFigmaからHTMLとCSSを出力するようなプラグインをつくってみたい

このとき、複数のモジュールを書いて一つのjsにまとめることになると思うのでwebpackを利用することにした

Figmaプラグインでのwebpackの利用については公式ドキュメントがある www.figma.com

ドキュメントではプラグイン実行時に表示されるui部分とFigmaに対して処理をするcode部分でエントリーポイントを分けて書かれているが、codeの結果をuiに反映させたいのでエントリーポイントはcode.tsだけにする

まずは必要なnpmモジュールのインストール

$ npm i -D webpack-cli ts-loader @babel/preset-typescript @babel/preset-env @babel/core

babel.config.js

module.exports = {
  presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript']
}

webpack.config.js

const path = require('path')

module.exports = (env, argv) => ({
  mode: argv.mode === 'production' ? 'production' : 'development',

  // This is necessary because Figma's 'eval' works differently than normal eval
  devtool: argv.mode === 'production' ? false : 'inline-source-map',

  entry: {
    code: './src/code.ts', // The entry point for your plugin code
  },

  module: {
    rules: [
      // Converts TypeScript code to JavaScript
      { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ },

      // Allows you to use "<%= require('./file.svg') %>" in your HTML code to get a data URI
      { test: /\.(png|jpg|gif|webp|svg)$/, loader: 'url-loader' },
    ],
  },

  // Webpack tries these extensions for you if you omit the extension like "import './file'"
  resolve: { extensions: ['.tsx', '.ts', '.jsx', '.js'] },

  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'), // Compile into a folder called "dist"
  }
})

package.json

  "scripts": {
    "dev": "webpack --mode=development --watch",
    "build": "webpack --mode=production"
  },

これでnpm run devで立ち上げておき、src/code.tsを編集すると自動でdist/code.jsに変換される仕組みができた

次はFigmaのnodeをhtmlやcssに変換する部分が書いていきたい