Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

답변: "개발환경에서 assets 파일 참조관련 질문" #70

Open
jeonghwan-kim opened this issue Dec 21, 2022 · 0 comments
Open

Comments

@jeonghwan-kim
Copy link
Owner

인프런 질문: 개발환경에서 assets 파일 참조관련 질문에 대한 답변입니다.

webpack.config.js:

const path = require("path");
// const { BannerPlugin, DefinePlugin } = require("webpack");
// const childProcess = require("child_process");
const HtmlWebpackPlugin = require("html-webpack-plugin");
// const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const isDevMode =
  (process.env.NODE_ENV || "development").trim() === "development";

console.log("is DEV mode?", isDevMode);
console.log("__dirname: ", __dirname);

module.exports = {
  mode: isDevMode ? "development" : "production",
  // entry: webpack 시작되는 부분이라고 생각하면 된다.
  entry: {
    main: "./src/index.js",
  },
  /**
   *  output
   * entry point를 기준으로
   * 모든 .js 파일을 합쳐서 하나의 bundle 파일로 만드는데,
   * 이걸 어디에 저장할 것인지 지정하는 option
   */
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: isDevMode ? "[name].js" : "main.[contenthash].js",
    chunkFilename: "[id].chunk.js",
    assetModuleFilename: "images/[hash][ext][query]",
    clean: true,
  },
  devServer: {
    port: 3000,
    hot: true,
    client: {
      overlay: {
        errors: true,
        warnings: false,
      },
    },
    // static: {
    //   directory: path.resolve(__dirname, './src/assets/'),
    // },
  },
  /**
   * module
   * test에 설정한 파일들을 inspect 하여,
   * 조건에 맞는 파일들에 대해 loader 들을 실행하여 해석함
   */
  module: {
    rules: [
      // {
      //   test: /\.(sa|sc|c)ss$/i,
      //   exclude: [/node_modules/],
      //   use: [
      //     // creates 'style' nodes from JS strings
      //     isDevMode
      //       ? 'style-loader'
      //       : {
      //           loader: MiniCssExtractPlugin.loader,
      //           options: {
      //             publicPath: '',
      //           },
      //         },
      //     // translates css into common JS
      //     'css-loader',
      //     'postcss-loader',
      //     // complies sass to css
      //     'sass-loader',
      //   ],
      // },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        exclude: [/node_modules/],
        type: "asset/resource",
        parser: {
          dataUrlCondition: {
            // 크기가 8kb 미만인 파일은 inline 모듈로 처리되고 그렇지 않으면 resource 모듈로 처리됩니다.
            maxSize: 4 * 1042,
          },
        },
        // generator: {
        //   publicPath: './assets/',
        //   outputPath: './assets/',
        // },
      },
      {
        test: /\.js$/,
        exclude: [/node_modules/],
        loader: "babel-loader",
      },
      // {
      //   test: /\.(woff|woff2|eot|ttf|otf)$/i,
      //   exclude: [/node_modules/],
      //   type: 'asset/resource',
      // },
    ],
  },
  plugins: [
    /**
     * 개발할 때 API 서버주소,
     * 배포했을 때 API 서버주소를 설정하는 Plugin
     */
    // new DefinePlugin({
    //   NODE_ENV: 'development',
    // }),
    //   new BannerPlugin({
    //     banner: `Build Date: ${new Date().toLocaleString()}
    //     Commit Version: ${childProcess.execSync('git rev-parse --short HEAD')}
    //     Author: ${childProcess.execSync('git config user.name')}`,
    //   }),
    new HtmlWebpackPlugin({
      template: "./public/index.html",
      templateParameters: {
        env: isDevMode ? "개발용" : "배포용",
      },
      minify: !isDevMode
        ? {
            collapseWhitespace: true,
            removeComments: true,
          }
        : false,
    }),
    //   ...(!isDevMode
    //     ? [
    //         new MiniCssExtractPlugin({
    //           filename: isDevMode ? '[name].css' : '[name].[contenthash].css',
    //           chunkFilename: isDevMode ? '[id].css' : '[id].[contenthash].css',
    //         }),
    //       ]
    //     : []),
  ],
};

src/index.js

// 이미지 파일도 모듈로 가져옵니다.
// 웹팩 module 설정에 이미지 파일에 대한 규칙을 추가했기 때문에 가능합니다.
// 이렇게 가져온 이미지파일을 빌드하면 아웃풋 폴더에 지정한 이름 규칙으로 파일이 생성될 것입니다.
import image from "./assets/image.png";

document.addEventListener("DOMContentLoaded", () => {
  const imgEl = document.createElement("img");
  imgEl.src = image;
  document.body.appendChild(imgEl);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant