0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

webpack

Last updated at Posted at 2024-10-21

▼webpackを使用する

1.
npm init -y

2.WebpackとWebpack CLIをインストール

npm install --save-dev webpack webpack-cli

3.ディレクトリ構造

my-project/
  ├── src/
  │   └── index.js  // エントリーポイント(アプリの起点)
  └── dist/
      └── bundle.js  // 出力ファイル

4.webpack.config.js設定ファイル

const path = require('path');
module.exports = {
  entry: './src/index.js', // エントリーポイント
  output: {
    filename: 'bundle.js', // 出力ファイル名
    path: path.resolve(__dirname, 'dist'), // 出力ディレクトリ
  },
  mode: 'development', // 開発モード
};

5.package.jsonでwebpack実行設定

{
  "name": "my-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack"
  },
  "devDependencies": {
    "webpack": "^5.0.0",
    "webpack-cli": "^4.0.0"
  }
}

6.実行

npm run build

▼自動で実行設定

1. 開発中にファイルを自動でリビルドしてくれるWebpack Dev Serverをインストール
npm install --save-dev webpack-dev-server

2.package.jsonに追加設定

"scripts": {
  "start": "webpack serve"
}

3.実行

npm start

▼gulpのwathとwebpack Dev serverの同時実行

1.concurrentlyパッケージツールをインストール
npm install concurrently --save-dev

2.package.jsonに追加設定

{
  "scripts": {
    "start": "concurrently \"npm run gulp\" \"npm run webpack\"",
    "gulp": "gulp",
    "webpack": "webpack serve"
  }
}

3.実行

npm start

wordpressにcssを読み込む

▼gulpで生成されたcssを読み込む

1.functions.phpに設定

  function my_theme_enqueue_styles() {
    wp_enqueue_style('main-styles', get_template_directory_uri() . '/public/css/style.css', array(), time());
  }
  add_action('wp_enqueue_scripts', 'my_theme_enqueue_styles');

headのlinkタグに読み込まず、functions.phpに記載する

wordpressにjsを読み込む

function my_custom_scripts() {
  // JavaScriptファイルを読み込む
  wp_enqueue_script(
    'my-script',
    get_template_directory_uri() . '/dist/bundle.js',
    array(),
    time(), // キャッシュを回避するため、バージョン番号に現在のタイムスタンプを使用
    true
);
}
add_action('wp_enqueue_scripts', 'my_custom_scripts');

footerに読み込み

<?php wp_footer(); ?>
</body>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?