このときはテンプレートをダウンロードしたときの実装済みの挙動を確認しただけだったが、今度はもう少し自分で書いて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
に変換される仕組みができた