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?

More than 1 year has passed since last update.

Webpack5を動かす記事

Posted at

はじめに

Webpackをちゃんと理解できたのでとりあえず動く「俺のタレ」を残しておく
ちゃんと理解したい人にはおすすめのUdemyのリンクを最下部に貼っておきます
ちなみにこの記事は学習した上で自分な理に必要な機能を取捨選択して組み直しまうのでご安心を!!書き方も変えてる
webppackの記事を書こうとしたら既に昔の自分が書いていた。死ぬほどわかりづらかった

この記事も仕事終わりのカフェでの勉強中にかいてる
殴り書き!! メモだから!!

## 手順と設定ファイルを書いていく

  1. npm init -y
  2. npm i -D webpack webpack-cli html-loader css-loader mini-css-extract-plugin html-webpack-plugin clean-webpack-plugin webpack-dev-server sass sass-loader
  3. mkdir src
  4. 起点のファイルでcssをimportする
  5. touch webpack.config.js

下記で、html,scss,js,画像の取り扱いに対応しています。
その際、htmlに直接cssや画像を記述するのではなく、dist/に綺麗に整頓された状態で出力されます
後述のbabelの設定も追加することで、ES6を古いブラウザで動くように変換できます。

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  devtool: "source-map",
  entry: "./src/js/main.js",
  output: {
    path: path.resolve(__dirname, "./dist"),
    filename: "js/main.js",
  },
  module: {
    rules: [
      {
        test: /\.(css|scss|sass)$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
      {
        test: /\.html/,
        use: "html-loader",
      },
      {
        test: /\.(png|jpg)/,
        type: "asset/resource",
        generator: {
          filename: "img/[name][ext]",
        },
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({ // css
      filename: "./css/main.css",
    }),
    new HtmlWebpackPlugin({ // html
      template: "./src/templates/index.html",
      filename: "index.html",
    }),
    new CleanWebpackPlugin(),
  ],
};

Babelの設定も追加

npm i -D babel-loader @babel/core
npm i -D @babel/preset-env
touch babel.config.json

webpack-config.js
// rulesの一番上に追加
// ぶっちゃけrulesの中ならどこでも良い
{ 
  test: /\.js$/, 
  exclude: /node_modules/, 
  loader: "babel-loader" 
}       
babel.config.json
// プロジェクトのルートに設定ファイル
{
  "presets": ["@babel/preset-env"]
}

おすすめ教材

Webpackの情報って結構出回ってます。
わかりにくい情報を含めてね。 この記事みたいな!!笑

下記Udemyは本当におすすめです
webpack4での構築ですが、webpackの設定方法をわかりやすく学べるので、自分でwebpac5も組めちゃうと思います。私は組めました!!

個人的に講座の中のpugは使わなくて良い気がする。
それと公式に合わせてるのかrulesの書き方が長い!! 自分で配列でまとめてます。

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?