symfony webpack導入
投稿日: 2024.01.04
1.なぜwebpackを使うのか?
近年Webサイトでは、レスポンス、UIの使いやすさなど利用者の求めるレベルが上がって来ております。そうなるとjavascript、cssなどが自然と増え管理または、ファイルが多くなってきてしまいます。また、そのままファイルを置いてしまうと簡単に技術が盗まれてしまいます。
こうした、問題を解決してくれるのがwebpackです。ファイルを圧縮し、解読しにくいファイルへと変換してくれます。また、プラグインなどの導入もしやすくなります。
2.webpackをインストール
composer require symfony/webpack-encore-bundle
yarn install
インストール後、assets
のフォルダとnode_module
のフォルダ、webpack.config.js
のファイルが生成されます。
webpack_encore:
# The path where Encore is building the assets - i.e. Encore.setOutputPath()
output_path: '%kernel.project_dir%/public/build'
# If multiple builds are defined (as shown below), you can disable the default build:
# output_path: false
# if using Encore.enableIntegrityHashes() and need the crossorigin attribute (default: false, or use 'anonymous' or 'use-credentials')
# crossorigin: 'anonymous'
# preload all rendered script and link tags automatically via the http2 Link header
# preload: true
# Throw an exception if the entrypoints.json file is missing or an entry is missing from the data
# strict_mode: false
# if you have multiple builds:
# builds:
# pass "frontend" as the 3rg arg to the Twig functions
# {{ encore_entry_script_tags('entry1', null, 'frontend') }}
# frontend: '%kernel.project_dir%/public/frontend/build'
# Cache the entrypoints.json (rebuild Symfony's cache when entrypoints.json changes)
# Put in config/packages/prod/webpack_encore.yaml
# cache: true
webpack_encore.yaml
が生成されております。ここでは、webpackで生成されたjs,css等がどこに出力されたかを記述する場所です。他にもいろいろ設定できますがまたの機会に説明できればと思います。
3.webpackに置き換える(twig)
scriptやcssなどをwebpackで生成したものへ置き換えていきます。
yarn add jquery
yarn add bootstrap
yarn add popper.js
インストール後app.js
にjquery
とbootstrap
の読み込みを行います。
/*
* Welcome to your app's main JavaScript file!
*
* We recommend including the built version of this JavaScript file
* (and its CSS file) in your base layout (base.html.twig).
*/
// any CSS you import will output into a single css file (app.css in this case)
// Need jQuery? Install it with "yarn add jquery", then uncomment to import it.
import $ from 'jquery';
// bootstrapのcssを読み込み
import 'bootstrap/dist/css/bootstrap.min.css';
// bootstrapのjsを読み込み
import 'bootstrap';
import './styles/app.css';
console.log('Hello Webpack Encore! Edit me in assets/app.js');
では、先ほどのlinkやscriptをwebpackに置き換えます。置き換えはとても簡単です。
{{ encore_entry_link_tags('app') }}
{{ encore_entry_script_tags('app') }}
置き換え後、webpackでjs,cssを生成します。
yarn build
webpackのファイルが実際どのように出力されているのでしょうか?少し見てみましょう。
<link rel="stylesheet" href="/build/0.6d3b7b6f.css">
<link rel="stylesheet" href="/build/app.53c6bc3a.css">
<script src="/build/runtime.d94b3b43.js"></script>
<script src="/build/0.0df20c72.js"></script>
<script src="/build/app.a54305f6.js"></script>
4.まとめ
今回は、webpackの導入について書きました。webpackを使用するとプラグインなどの導入も凄く楽に助かっています。しかし、今までtwig等にjsを書いていた人なので中々使いなれるのにはすごく時間が掛かりました。ですが、今後webpackは必須の技術になってくると思うのでぜひ試してみてください。