Giter VIP home page Giter VIP logo

lecture-frontend-dev-env's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

lecture-frontend-dev-env's Issues

윈도우 환경 NODE_ENV 명령 실행 안될때 cross-env패키지로 해결

안녕하세요? 녹화된 영상으로 프론트엔드 개발 환경 이해를 듣고 있습니다.
많은 분들이 아실지도 모르지만 저와 같은 초보자를 위해 이렇게 글을 씁니다.
윈도우 환경에서 NODE_ENV=production && npm run build 명령은 실행되지 않습니다.

이를 실행하기 위해서 cross-env 패키지를 설치해주고 package.json script"build": cross-env set NODE_ENV=production npm run build를 설정해주고 해당 명령을 쳐야 실행됩니다.

이 부분을 추가해주시면 저와 같은 또다른 초심자에게 도움이 될거 같아 글을 남깁니다.

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

인프런 질문: 개발환경에서 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);
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.