Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Aug 8, 2019. It is now read-only.
/docsPublic archive
Eddie Flores edited this pageSep 19, 2017 ·30 revisions

INSTALLATION

You can install webpack via npm:

npm install webpack -g

Note: We’re installing webpack globally for demonstration purposes. When you are building a real application, it’s more advisable to install webpack as adevDependency of your project.

GETTING STARTED

First, we’ll learn the basics of webpack by using just webpack’s command-line interface.

Create a modular JavaScript project

Let’s create some modules in JavaScript, using the CommonJs syntax:

cats.js

var cats = ['dave', 'henry', 'martha'];module.exports = cats;

app.js (Entry Point)

cats = require('./cats.js');console.log(cats);

The "entry point" is where your application will start, and where webpack will start tracking dependencies between modules.

webpack in 5 seconds

Give webpack the entry point (app.js) and specify an output file (app.bundle.js):

webpack ./app.js app.bundle.js

webpack will read and analyze the entry point and its dependencies (including transitive dependencies). Then it will bundle them all intoapp.bundle.js.

Now your bundle is ready to be run. Runnode app.bundle.js and marvel in your abundance of cats.

node app.bundle.js["dave", "henry", "martha"]

You can also use the bundle in the browser.

GETTING SERIOUS

webpack is a very flexible module bundler. It offers a lot of advanced features, but not all features are exposed via the command-line interface. To gain full access to webpack’s flexibility, we need to create a "configuration file".

Project structure

In real-world webpack projects, we’ll separate the source files from the bundled files by organizing them in folders. For example, we’ll put the source files insrc, and bundled files inbin.

Our final project structure will look like this:

In the wild, there are many project structures. Some projects useapp instead ofsrc. Some projects usedist orbuild instead ofbin. Projects with tests usually usetest,tests,spec,specs or colocate the test files in the source folder.

  1. Create thebin andsrc directory.

    mkdir binmkdir src
  2. Move the original source files to thesrc folder.

    mv app.js cats.js src
  3. Initialize an npm project.

    npm init # (answer the questions)
  4. Install webpack as a development dependency. This lets your project declare the version of webpack it is compatible with.

    npm install --save-dev webpack

Moving to a configuration file.

As your project grows and your configuration becomes more complex, it becomes unwieldy to configure webpack from the command line. Let’s create a configuration file instead.

  1. Createwebpack.config.js:

    constpath=require('path');module.exports={entry:'./src/app.js',output:{path:path.resolve(__dirname,'bin'),filename:'app.bundle.js'}};

    A webpack configuration file is a CommonJS-style module. So you can run any kind of code here, as long as a configuration object is exported out of this module.

  2. With the configuration file in place, you can now simply run webpack like this:

    webpack

    webpack will read the configuration file, build the bundle, and save it asbin/app.bundle.js. If you examine webpack's output you'll see that it included both source files.

  3. Runbin/app.bundle.js and you'll get your list of cats again.

    node bin/app.bundle.js["dave", "henry", "martha"]

You can alsorequire() modules installed via npm with no extra configuration.

Using loaders

webpack only supports JavaScript modules natively, but most people will be using a transpiler for ES2015, CoffeeScript, TypeScript, etc. They can be used in webpack by usingloaders.

Loaders are special modules webpack uses to 'load' other modules (written in another language) into JavaScript (that webpack understands). For example,babel-loader uses Babel to load ES2015 files.

json-loader loads JSON files (simply by prependingmodule.exports = to turn it into a CommonJs module).

Loaders can be chained, and sometimes you need to chain loaders together. For example,yaml-loader only converts YAML into JSON. Therefore, you need to chain it withjson-loader so that it can be used.

Transpiling ES2015 usingbabel-loader

In this example, we're going to tell webpack to run our source files throughBabel so we can use ES2015 features.

  1. Install Babel and the presets:

    npm install --save-dev babel-core babel-preset-es2015
  2. Installbabel-loader:

    npm install --save-dev babel-loader
  3. Configure Babel to use these presets by adding.babelrc

    { "presets": [ "es2015" ] }
  4. Modifywebpack.config.js to process all.js files usingbabel-loader.

    constpath=require('path');module.exports={entry:'./src/app.js',output:{path:path.resolve(__dirname,'bin'),filename:'app.bundle.js',},module:{loaders:[{test:/\.js$/,exclude:/node_modules/,loader:'babel-loader'}]}}

    We are excludingnode_modules here because otherwise all external libraries will also go through Babel, slowing down compilation.

  5. Install the libraries you want to use (in this example, jQuery):

    npm install --save jquery babel-polyfill

    We are using--save instead of--save-dev this time, as these libraries will be used in runtime. We also usebabel-polyfill so that ES2015 APIs are available in older browsers.

  6. Editsrc/app.js:

    import'babel-polyfill';importcatsfrom'./cats';import$from'jquery';$('<h1>Cats</h1>').appendTo('body');constul=$('<ul></ul>').appendTo('body');for(constcatofcats){$('<li></li>').text(cat).appendTo(ul);}
  7. Bundle the modules using webpack:

    webpack
  8. Addindex.html so this app can be run in browser:

    <!DOCTYPE html><html><head><metacharset="utf-8"></head><body><scriptsrc="bin/app.bundle.js"charset="utf-8"></script></body></html>

When you openindex.html, you should now see a list of cats!

There are a number ofdifferent loaders you can use to include files in your app bundle, including css and image loaders.

Using plugins

Usually you'll want to do some additional processing of the bundle in your workflow. An example would be minifying your file so that clients can load it faster. This can be done withplugins. We'll add the uglify plugin to our configuration:

const webpack = require('webpack');module.exports = {entry: './src/app.js',output: {path: './bin',filename: 'app.bundle.js',},module: {loaders: [{test: /\.js?$/,exclude: /node_modules/,loader: 'babel-loader',}]},plugins: [new webpack.optimize.UglifyJsPlugin({compress: {warnings: false,},output: {comments: false,},}),]}

The Uglify plugin is included with webpack so you don't need to add additional modules, but this may not always be the case. You can write your owncustom plugins. For this build, the uglify plugin cut the bundle size from 1618 bytes to 308 bytes.

FURTHER READING

webpack 👍

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp