[๐Ÿ“š ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ] Webpack ์‚ฌ์šฉ๋ฒ•

dsfasdยท2022๋…„ 11์›” 23์ผ
0

์›นํŒฉ ๊ธฐ๋ณธ ์‚ฌ์šฉ๋ฒ• ์˜ˆ์ œ

1. ํ”„๋กœ์ ํŠธ ํ™ˆ ๊ฒฝ๋กœ์—์„œ npm init์œผ๋กœ package.json ํŒŒ์ผ์„ ์ƒ์„ฑํ•˜๊ธฐ.

npm init -y

์›นํŒฉ์€ ์‚ฌ์šฉํ•  ์—ฌ๋Ÿฌ ํŒŒ์ผ๋“ค์„ ํ•˜๋‚˜๋กœ ์••์ถ•์‹œ์ผœ์ฃผ๋Š” ๊ฒƒ์ž„!

2. ์••์ถ• ์‹œํ‚ฌ ํŒŒ์ผ๋“ค์„ ์ค€๋น„ํ•˜๊ธฐ

-> src ํด๋” ์ƒ์„ฑ ํ›„, index.jsํŒŒ์ผ๊ณผ underbar.js ํŒŒ์ผ์„ ๊ฐ๊ฐ ์ƒ์„ฑ

// src/index.js
const _ = require('./underbar.js')

const shout = (...sentences) => console.log(...sentences);

const loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis egestas feugiat elit, ac tincidunt neque vestibulum at. Mauris a eros sit amet urna efficitur tempus."

const shoutOnce = _.once(shout);

shoutOnce(loremIpsum);
shoutOnce(loremIpsum);
shoutOnce(loremIpsum);
shoutOnce(loremIpsum);
// src/underbar.js
const _ = {
  once(func) {
    // ์•„๋ž˜ ๋ณ€์ˆ˜๋“ค์€ ์•„๋ž˜ ์„ ์–ธ/๋ฆฌํ„ด๋˜๋Š” ํ•จ์ˆ˜ ์•ˆ์—์„œ ์ฐธ์กฐ๋ฉ๋‹ˆ๋‹ค.
    // ๋ฆฌํ„ด๋˜๋Š” ํ•จ์ˆ˜์˜ scope ๋‚ด์— ์กด์žฌํ•˜๋ฏ€๋กœ, ๋ฆฌํ„ด๋˜๋Š” ํ•จ์ˆ˜๋ฅผ ์–ธ์ œ ์‹คํ–‰ํ•ด๋„ ์ด ๋ณ€์ˆ˜๋“ค์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    let result;
    let alreadyCalled = false;

    return function (...args) {
      // TIP: arguments ํ‚ค์›Œ๋“œ ํ˜น์€, spread operator๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”.
      if (!alreadyCalled) {
        alreadyCalled = true;
        result = func(...args);
      }
      return result;
    };
  },
};

module.exports = _; // ๋‹ค๋ฅธ ํŒŒ์ผ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๊ฒŒ export

3. ์›นํŒฉ ์„ค์น˜ํ•˜๊ธฐ ๋ฐ ์›นํŒฉ config ํŒŒ์ผ ์ž‘์„ฑํ•˜๊ธฐ.

์›นํŒฉ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ ์›นํŒฉ์„ ์„ค์น˜ํ•œ๋‹ค.

cf. -D : devDependency์˜ต์…˜์„ ์„ค์ •

dependencies ์— ์„ค์น˜๋œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” ๋ฐฐํฌํ•  ๋•Œ ํฌํ•จ๋˜์ง€๋งŒ
devDependencies ์— ์„ค์น˜๋œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” ๊ฐœ๋ฐœํ•  ๋•Œ ํ•„์š”ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐฐํฌํ•  ๋•Œ ํฌํ•จ๋˜์ง€๋Š” ์•Š๋Š”๋‹ค.

์›นํŒฉ ์„ค์น˜

npm install -D webpack webpack-cli

์›นํŒฉ config ํŒŒ์ผ ์ž‘์„ฑ

ํŒŒ์ผ์˜ ๋ฃจํŠธ ๊ฒฝ๋กœ์— ์ž‘์„ฑํ•œ๋‹ค.

// webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'), // './dist'์˜ ์ ˆ๋Œ€ ๊ฒฝ๋กœ๋ฅผ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
    filename: 'app.bundle.js',
  },
};

4. ๋ฒˆ๋“ค๋ง ํ•˜๊ธฐ

๋ฒˆ๋“ค๋ง์„ ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ช…๋ น์–ด๋ฅผ ์ž…๋ ฅํ•œ๋‹ค.

npx webpack

๋ฒˆ๋“ค๋ง ์„ฑ๊ณต์‹œ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฌธ๊ตฌ๋“ค์ด ๋‚˜์˜จ๋‹ค.
๋ฒˆ๋“ค๋ง์‹œ ์ƒ์„ฑ๋œ ํŒŒ์ผ์€ ๋น ๋ฅด๊ฒŒ ํŒŒ์ผ์„ ์ „๋‹ฌํ•˜๊ธฐ ์œ„ํ•ด์„œ ์ตœ์†Œํ™”๋œ ์ฝ”๋“œ๋กœ,
์•Œ์•„๋ณด๊ธฐ ํž˜๋“ค๊ฒŒ ์ž‘์„ฑ๋˜์–ด ์žˆ๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

node๋กœ ๋ฒˆ๋“ค๋งํ•œ app.bundle.js ํŒŒ์ผ์˜ ๊ฒฐ๊ณผ์™€
์—”ํŠธ๋ฆฌ ํฌ์ธํŠธ๋กœ ์ง€์ •ํ•œ src/index.js ํŒŒ์ผ ์‹คํ–‰๊ฒฐ๊ณผ์™€ ๋™์ผํ•˜๋ฉด ์„ฑ๊ณต์ด๋‹ค.

node dist/app.bundle.js

5. npm run build ์„ค์ •ํ•˜๊ธฐ

package.json ํŒŒ์ผ์˜ script์— ์•„๋ž˜์™€ ๊ฐ™์ด ์ž‘์„ฑํ•ด๋‘๋ฉด
npm run build ๋ช…๋ น์‹œ ์‰ฝ๊ฒŒ ๋ฒˆ๋“ค๋ง์„ ํ•  ์ˆ˜ ์žˆ๋‹ค.

profile
๊ธฐ๋ก์„ ์ •๋ฆฌํ•˜๋Š” ๊ณต๊ฐ„!

0๊ฐœ์˜ ๋Œ“๊ธ€