>  기사  >  웹 프론트엔드  >  웹팩 패키저에 대한 간략한 소개

웹팩 패키저에 대한 간략한 소개

零下一度
零下一度원래의
2017-06-26 10:37:231752검색

Concept

webpack은 최신 자바스크립트 애플리케이션을 위한 모듈 번들러입니다.

webpack이 애플리케이션을 처리할 때 종속성 그래프(애플리케이션에 필요한 모든 모듈 포함)를 반복적으로 구축한 다음 이러한 모듈을 몇 개의 Budle 파일로 패키징합니다(프로젝트에 따라 일반적으로 하나만 브라우저에 의해 로드됨). 정황).

이것은 놀라운 구성이지만 시작하기 전에 항목, 출력, 로더 및 플러그인의 네 가지 핵심 개념만 이해하면 됩니다.

구성 개체 옵션
webpack.config.js

const path = require('path');

module.exports = {
  // click on the name of the option to get to the detailed documentation
  // click on the items with arrows to show more examples / advanced options

  entry: "./app/entry", // string | object | array
  // Here the application starts executing
  // and webpack starts bundling

  output: {
    // options related to how webpack emits results

    path: path.resolve(__dirname, "dist"), // string
    // the target directory for all output files
    // must be an absolute path (use the Node.js path module)

    filename: "bundle.js?1.1.11", // string
    // the filename template for entry chunks

    publicPath: "/assets/", // string
    // the url to the output directory resolved relative to the HTML page

    library: "MyLibrary", // string,
    // the name of the exported library

    libraryTarget: "umd", // universal module definition
    // the type of the exported library

    /* Advanced output configuration (click to show) */
  },

  module: {
    // configuration regarding modules

    rules: [
      // rules for modules (configure loaders, parser options, etc.)

      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, "app")
        ],
        exclude: [
          path.resolve(__dirname, "app/demo-files")
        ],
        // these are matching conditions, each accepting a regular expression or string
        // test and include have the same behavior, both must be matched
        // exclude must not be matched (takes preferrence over test and include)
        // Best practices:
        // - Use RegExp only in test and for filename matching
        // - Use arrays of absolute paths in include and exclude
        // - Try to avoid exclude and prefer include

        issuer: { test, include, exclude },
        // conditions for the issuer (the origin of the import)

        enforce: "pre",
        enforce: "post",
        // flags to apply these rules, even if they are overridden (advanced option)

        loader: "babel-loader",
        // the loader which should be applied, it'll be resolved relative to the context
        // -loader suffix is no longer optional in webpack2 for clarity reasons
        // see webpack 1 upgrade guide

        options: {
          presets: ["es2015"]
        },
        // options for the loader
      },

      {
        test: "\.html$",

        use: [
          // apply multiple loaders and options
          "htmllint-loader",
          {
            loader: "html-loader",
            options: {
              /* ... */
            }
          }
        ]
      },

      { oneOf: [ /* rules */ ] },
      // only use one of these nested rules

      { rules: [ /* rules */ ] },
      // use all of these nested rules (combine with conditions to be useful)

      { resource: { and: [ /* conditions */ ] } },
      // matches only if all conditions are matched

      { resource: { or: [ /* conditions */ ] } },
      { resource: [ /* conditions */ ] },
      // matches if any condition is matched (default for arrays)

      { resource: { not: /* condition */ } }
      // matches if the condition is not matched
    ],

    /* Advanced module configuration (click to show) */
  },

  resolve: {
    // options for resolving module requests
    // (does not apply to resolving to loaders)

    modules: [
      "node_modules",
      path.resolve(__dirname, "app")
    ],
    // directories where to look for modules

    extensions: [".js?1.1.11", ".json", ".jsx", ".css?1.1.11"],
    // extensions that are used

    alias: {
      // a list of module name aliases

      "module": "new-module",
      // alias "module" -> "new-module" and "module/path/file" -> "new-module/path/file"

      "only-module$": "new-module",
      // alias "only-module" -> "new-module", but not "module/path/file" -> "new-module/path/file"

      "module": path.resolve(__dirname, "app/third/module.js?1.1.11"),
      // alias "module" -> "./app/third/module.js?1.1.11" and "module/file" results in error
      // modules aliases are imported relative to the current context
    },
    /* alternative alias syntax (click to show) */

    /* Advanced resolve configuration (click to show) */
  },

  performance: {
    hints: "warning", // enum
    maxAssetSize: 200000, // int (in bytes),
    maxEntrypointSize: 400000, // int (in bytes)
    assetFilter: function(assetFilename) {
      // Function predicate that provides asset filenames
      return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
    }
  },

  devtool: "source-map", // enum
  // enhance debugging by adding meta info for the browser devtools
  // source-map most detailed at the expense of build speed.

  context: __dirname, // string (absolute path!)
  // the home directory for webpack
  // the entry and module.rules.loader option
  //   is resolved relative to this directory

  target: "web", // enum
  // the environment in which the bundle should run
  // changes chunk loading behavior and available modules

  externals: ["react", /^@angular\//],
  // Don't follow/bundle these modules, but request them at runtime from the environment

  stats: "errors-only",
  // lets you precisely control what bundle information gets displayed

  devServer: {
    proxy: { // proxy URLs to backend development server
      '/api': 'http://localhost:3000'
    },
    contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location
    compress: true, // enable gzip compression
    historyApiFallback: true, // true for index.html upon 404, object for multiple paths
    hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
    https: false, // true for self-signed, object for cert authority
    noInfo: true, // only errors & warns on hot reload
    // ...
  },

  plugins: [
    // ...
  ],
  // list of additional plugins


  /* Advanced configuration (click to show) */
}

이 문서의 목적은 이러한 개념에 대한 높은 수준의 개요를 제공하는 동시에 자세한 개념에 대한 특정 사용 사례에 대한 링크를 제공하는 것입니다.

Entry

webpack은 모든 애플리케이션의 종속성 그래프를 생성합니다. 이 종속성 그래프의 시작점은 알려진 진입점입니다. 이 진입점은 알려진 종속성 그래프를 기반으로 webpack을 시작하고 패키징할 위치를 알려줍니다. 애플리케이션의 진입점을 컨텍스트 루트 또는 애플리케이션을 시작하는 첫 번째 파일로 생각할 수 있습니다.

webpack 구성 객체의 진입 속성에 진입점을 정의하세요. 간단한 예는 다음과 같습니다.

module.exports = {
  entry: './path/to/my/entry/file.js'
};

항목 속성을 선언하는 방법에는 여러 가지가 있습니다.

1. 단일 항목 구문

const config = {
  entry: './path/to/my/entry/file.js'
};

module.exports = config;

2. 다중 페이지 응용 프로그램

const config = {
  entry: {
    app: './src/app.js',
    vendors: './src/vendors.js'
  }
};

Output

모든 코드를 패키징한 후에도 webpack에 패키징할 위치를 알려주어야 합니다. 출력 속성은 웹팩에 코드 처리 방법을 알려줍니다.

const config = {
  entry: {
    pageOne: './src/pageOne/index.js',
    pageTwo: './src/pageTwo/index.js',
    pageThree: './src/pageThree/index.js'
  }
};

위의 예에서는

속성을 사용하여 webpack에 패키지된 파일 이름과 경로를 알려줍니다.

output.filenameoutput.path더 많은 구성 항목

Loaders

이 구성 항목의 목적은 webpack이 패키지 파일 이름과 경로에 주의를 기울이도록 하는 것입니다. 브라우저가 아닌 프로젝트에 저장됩니다(이것이 함께 패키지된다는 의미는 아닙니다). webpack은 각 파일(.css, .html, .scss, .jpg 등)을 모듈로 처리합니다. 하지만 웹팩은 자바스크립트만 알고 있습니다.

webpack의 로더는 이러한 파일을 모듈로 변환하고 종속성 그래프에 추가합니다.

상위적으로 웹팩 구성에는 두 가지 목적이 있습니다.

1 특정 로더로 변환해야 하는 파일을 식별합니다.

2. 변환된 파일을 종속성 그래프에 추가할 수 있습니다.

const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  }
};

위 구성은 별도의 모듈에 대한 규칙 속성을 정의합니다. 이 모듈에는 테스트와 사용이라는 두 가지 속성이 있습니다. 이는 webpack이 다음 사항을 컴파일하도록 지시합니다. require() 또는 import 문을 사용할 때 경로에 .js 또는 .jsx 접미사가 있는 파일은 babel-loader를 사용하여 변환 및 패키징됩니다.


추가 구성 항목

플러그인

로더는 파일별로만 변환을 수행하기 때문에 플러그인은 동작을 최적화하기 위해 가장 일반적으로 사용되지만 이에 국한되지 않으며 편집 또는 블록에서 기능을 사용자 정의할 수 있습니다. 패키지 모듈 매체(등).

webpack 플러그인 시스템은 매우 강력하고 사용자 정의가 가능합니다.


플러그인을 사용하려면 require()를 하고 플러그인 배열에 추가하기만 하면 됩니다. 옵션을 사용하여 더 많은 플러그인을 사용자 정의할 수 있습니다. 다양한 목적으로 구성에서 플러그인을 여러 번 사용할 수 있으므로 새 인스턴스를 생성해야 합니다.

const path = require('path');

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      {test: /\.(js|jsx)$/, use: 'babel-loader'}
    ]
  }
};

module.exports = config;

webpack은 즉시 사용 가능한 다양한 플러그인을 제공합니다! 자세한 내용은 플러그인 목록에서 확인할 수 있습니다.

웹팩 구성에서 플러그인을 사용하는 것은 간단하지만 더 자세히 살펴볼 가치가 있는 사용법이 많이 있습니다.

추가 구성 항목

간단한 예

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
const path = require('path');

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      {test: /\.txt$/, use: 'raw-loader'}
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

module.exports = config;

위 내용은 웹팩 패키저에 대한 간략한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.