Szukaj…


Uwagi

Webpack to pakiet modułów, który odczytuje moduły z zależnościami i tworzy statyczne zasoby reprezentujące te moduły.

Posiada rozszerzalny system ładujący, który pozwala pakietom zawierać nie tylko zasoby Javascript, ale także CSS, obrazy, HTML i wiele więcej.

Na przykład za pomocą wbudowanego modułu ładującego JavaScript, modułu ładującego css i modułu ładującego adres URL :

require("./code.js") // Load Javascript dependency
var css = require("./styles.css"); // Load CSS as a string
var base64Image = require("./image.png"); // Load an image as a base64 string

Stałby się jednym plikiem w pakiecie:

// From code.js
console.log("Hello, World");
// From styles.css
var css = "body { margin: 0; padding: 0; } h1 { color: #FF0000; }";
// From image.png
var base64Image = "data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX...";

Zależności można zdefiniować w dowolnym z najpopularniejszych stylów modułów (CommonJS i AMD).

Wersje

Wersja Data wydania
3.0.0 2017-06-19
2.6.1 2017-05-25
2.6.0 23.05.2017
2.5.1 2017-05-07
2.5.0 2017-05-04
2.4.1 14.04.2017
2.4.0 14.04.2017
1.13 17.04.2016
1.12 25.08.2015
1.11 2015-08-06
1.10 27.06.2015
1.9 2015-05-10
1.8 2015-04-29
1.7 2015-03-11
1.6 24.02.2015
1.5 21.01.2015
1.4 28.12.2014
1.3 25.08.2014
1.2 27.05.2014
1.1 17.05.2014
1.0 01.03.2014
0,11 31.12.2013
0,10 19.06.2013
0,9 19.03.2013
0,8 21.01.2013

Instalacja

Wymagania wstępne:

NodeJS i npm

Istnieją dwa sposoby instalowania pakietu Webpack: globalnie lub dla jednego projektu. Najlepiej jest mieć zależność zainstalowaną dla każdego projektu, ponieważ pozwoli to na użycie różnych wersji pakietu dla każdego projektu i nie będzie wymagać, aby użytkownik zainstalował pakiet na całym świecie.

Instalowanie na projekt

Uruchom następujące polecenie z folderu głównego swojego projektu:

npm install webpack --save-dev

Następnie możesz uruchomić plik wykonywalny node_modules zainstalowany w node_modules :

./node_modules/.bin/webpack

Lub stwórz skrypt NPM w pliku package.json , w którym możesz pominąć część node_modules - npm jest wystarczająco inteligentny, aby dołączyć ten folder do PATH.

// in package.json:
{
  ...
  "scripts": {
    "start": "webpack"
  },
  ...
}

// from terminal:
npm start

Instaluje się globalnie

Uruchom następujące polecenie w wierszu polecenia:

npm install webpack -g

Przykład webpack.config.js z babel

Zależności

npm i -D webpack babel-loader

webpack.config.js

const path = require('path');

module.exports = {
  entry: {
    app: ['babel-polyfill', './src/'],
  },
  output: {
    path: __dirname,
    filename: './dist/[name].js',
  },
  resolve: {
    extensions: ['', '.js'],
  },
  module: {
    loaders: [{
      test: /\.js$/, 
      loaders: ['babel-loader'],
      include: path.resolve(__dirname, 'src')
    }],
  }
};

Przykład Javascript + CSS + czcionki + obrazy

Wymagane moduły

npm install --save-dev webpack extract-text-webpack-plugin file-loader css-loader style-loader

Struktura folderów

.
└── assets
    ├── css
    ├── images
    └── js

webpack.config.js

const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const glob = require('glob');

module.exports = {
  entry: {
    script: path.resolve(__dirname, './assets/js/app.js'),
    style: path.resolve(__dirname, './assets/css/app.css'),
    images: glob.sync(path.resolve(__dirname, './assets/images/**/*.*')),
  },
  context: __dirname,
  output: {
    path: path.resolve('./dist/assets'),
    publicPath: '/dist/assets',
    filename: '[name].js',
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: 'css-loader'
        }),
      },
      {
        test: /(\.woff2?|\.woff|\.ttf|\.eot|\.svg)(\?v=\d+\.\d+\.\d+)?$/,
        loader: 'file-loader?name=[name]-[hash:6].[ext]',
      },
      {
        test: /\.(png|jpe?g|gif|ico)$/,
        loader: 'file-loader?name=[name].[ext]',
      },
    ],
  },
  plugins: [
    new ExtractTextPlugin('app.css' /* optional: , { allChunks: true } */),
  ],
};

glob.sync('./assets/images/**/*.*') będzie wymagał wszystkich plików w folderze obrazów jako pozycji.

ExtractTextPlugin pobierze wygenerowane dane wyjściowe i utworzy dołączony plik css .

Prosty przykład pakietu Webpack

Minimum wymagane do korzystania z pakietu Webpack to następujące polecenie:

webpack ./src/index.js ./dist/bundle.js

// this is equivalent to:

webpack source-file destination-file

Pakiet WWW pobierze plik źródłowy, skompiluje do miejsca docelowego i rozwiąże wszelkie zależności w plikach źródłowych.

Webpack, React JSX, Babel, ES6, prosta konfiguracja

Upewnij się, że instalujesz prawidłowe zależności npm (babel postanowił podzielić się na kilka pakietów, co ma związek z „zależnościami równorzędnymi”):

npm install webpack webpack-node-externals babel-core babel-loader babel-preset-react babel-preset-latest --save

webpack.config.js :

module.exports = {
    context: __dirname, // sets the relative dot (optional)
    entry: "./index.jsx",
    output: {
        filename: "./index-transpiled.js"
    },
    module: {
        loaders: [{
            test: /\.jsx$/,
            loader: "babel?presets[]=react,presets[]=latest" // avoid .babelrc
        }]
    }, // may need libraryTarget: umd if exporting as a module
    externals: [require("webpack-node-externals")()], // probably not required
    devtool: "inline-source-map"
};

webpack-node-externals to funkcja, która skanuje twoje node_modules i upewnia się, że nie są one transpilowane i pakowane wraz z twoim kodem front-end, chociaż zapewnia, że pakiet zachowuje do nich odniesienia. Pomaga to w szybszej transpilacji, ponieważ nie ponownie kodujesz bibliotek.

Prosta konfiguracja webpacka za pomocą Node.js

Struktura folderów

.
├── lib
├── modules
|   ├── misc.js
|   ├── someFunctions.js
├── app.js
├── index.html
├── package.json
├── webpack.config.js
└── webserver.js   

pakiet.json

{
  "name": "webpack-example-with-nodejs",
  "version": "1.0.0",
  "description": "Example using webpack code-splitting with some Node.js to support the example",
  "main": "webserver.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "@Gun",
  "license": "ISC",
  "devDependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.15.2",
    "http": "0.0.0",
    "morgan": "^1.8.1",
    "multer": "^1.3.0",
    "webpack": "^2.4.1"
  }
}

webpack.config.js

var path = require('path'); // used to get context

module.exports = {
    context: path.join(__dirname, 'app'), // resolves entry below, must be absolute path
    entry: './app.js', // entry point or loader for the application
    output: {
        path: path.join(__dirname, 'app/lib'), // express static folder is at /app/lib
        filename: '[name].bundle.js', // the file name of the bundle to create.  [name] is replaced by the name of the chunk (code-splitting)
        publicPath: 'static' // example uses express as the webserver
    }
};

webserver.js

var express = require('express'),
    path = require('path'),
    bodyParser = require('body-parser'),
    multer = require('multer')()
    logger = require('morgan'),
    fs = require('fs'),
    http = require('http');

var app = express();
var port = 31416;

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('short'));
app.use('/jsBundles',express.static('lib'));
app.get('/', function(request, response){
    response.sendFile(__dirname + '/index.html');
});

var server = http.createServer(app).listen(port, function(){
    console.log("I feel a disturbance in the port:" + port);
});

index.html

<!DOCTYPE html>
<html>
    <body>
        <div id="someValue"><label for="num">Enter a number:</label><input id="num" /></div>
        <div class="buttonList">
            <ul>
                <li><button id="doubleIt">double it</button></li>
                <li><button id="tripleIt">triple it</button></li>
            </ul>
        </div>
        <div id="someOtherValue">
            And the count shall be: <span id="theCount"></span>
        </div>
        <script src="/jsBundles/main.bundle.js"></script>        
    </body>
</html>

app.js

require(['./modules/someFunctions'],function(){
        window.onload = function(){
                var someFunctions  = require('./modules/someFunctions');             
                document.getElementById('doubleIt').onclick = function(){
                        var num = document.getElementById('num').value;
                        document.getElementById('theCount').innerHTML = someFunctions.Double(num);
                };

                document.getElementById('tripleIt').onclick = function(){
                        var num = document.getElementById('num').value;
                        document.getElementById('theCount').innerHTML = someFunctions.Triple(num);
                };
        };
});

misc.js

var self = {};
self.isNumber = function(value){
    // http://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
    return !isNaN(parseFloat(value)) && isFinite(value);
};
module.exports = self;

someFunctions.js

require(['./misc'], function(){
    var misc= require('./misc');

    var self = {};
    self.Double = function(value){
        if(!misc.isNumber(value)){
            return 0;
        };
        return value*2;
    }

    self.Triple = function(value){
        if(!misc.isNumber(value)){
            return 0;
        };
        return value*3;
    }

    module.exports = self;
});

UWAGA

uruchom npm i --save-dev, aby zainstalować zależności

uruchom węzeł. \ node_modules \ webpack \ bin \ webpack.js po zainstalowaniu zależności

uruchom węzeł webserver.js, aby uruchomić serwer



Modified text is an extract of the original Stack Overflow Documentation
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow