I’ve been using WebPack for almost a year now, building 4 or 5 projects with it, stomping through a few potholes, and documenting it with my own understanding.

I will now show you how to build a multi-page project developed by WebPack step by step. The project address of this article is github.com/fe-config/g…

First you need to install:

git clone https://github.com/fe-config/generate-pages-tutorial 

Webpack 1.x is used here

Note the webpack.config.js and pageage.json for each step

Basic JavaScript module processing

cd 1_multi_pages
npm install
npm run build

You can configure multiple entries in webpack.config.js, and you can see the compiled file generated under dist:

|--- dist
        |--- page1
                |--- main.js
        |--- page2
                |--- main.js
Copy the code

The directory level here corresponds to the module names in Entry (page1/main, page2/main).

Open page1.html and page2.html to see our JS module in effect. Now on to the next step!

2. Processing of CSS modules

From the previous step, we solved the problem of JavaScript modules, and the page also has CSS. Webpack only handles JavaScript by default, so we’ll introduce CSS-loader and style-loader to handle CSS.

cd 2_css
npm install
npm run build

CSS

{
    test: /\.css$/,
    loaders: ['style', 'css']
}

Loader is a processor that specializes in processing certain modules. Webpack can only handle JS, in order to be able to handle CSS, you need CSS-loader; To be able to insert CSS into a page, you need a style-loader.

Open page1. HTML to see the CSS in effect.

less

{
    test: /\.less$/,
    loaders: ['style', 'css', 'less']
}

If less is used, you need to install less and less-loader.

Open page2.html to see less in effect.

sass

{
    test: /\.scss$/,
    loaders: ['style', 'css', 'sass']
}

If sASS is used, you need to install Node-sass and sass-Loader.

Open page3.html to see less in effect.

postcss

module: {
    loaders: [
        {
            test: /\.css$/,
            include: ROOT + '/src/page4',
            loaders: ['style', 'css', 'postcss']
        }
    ]
},
postcss: function() {
    return [autoprefixer]
}

If sASS is used, postCSS-Loader needs to be installed. The following uses autoprefixer as an example.

Open page4.html to see less in effect.

Generating CSS Files

All of the above methods use JS to generate CSS, but what we really need is a CSS file, which can be solved using the extract-text-webpack-plugin.

Open page5.html to see the effect

Third, reload

Now that we’ve learned how to handle the JS and CSS modules and have CSS generate files independently of each other in the previous two sections, we feel that the process of changing the code and then building and refreshing the browser is too slow, and there’s no need to generate a new file every time you change a line of code, which is the main reason for the slow build.

Webpack-dev-server is a development server that comes with Webpack, supporting hot replacement, proxies, and so on.

cd 3_reload
npm install
npm run dev

Open 0.0.0.0:8888/page1. HTML and you’ll see the page. And whenever you modify main.js, style.css, or TPL /page1. HTML, the browser will automatically refresh.

Here we use:

  • Html-webpack-plugin: Automatically injects JS and CSS into pages
  • Html-webpack-harddisk-plugin: change every timepages/tplInside the file when it is automatically inpages/htmlGenerate the corresponding file in
  • Raw – loader: okrequireHTML file, so that every time the TPL file is modified, the browser automatically refreshes the page

It is also worth noting that since the Reload function is required at development time, we need to leave this out during build time. Cross-env and DefinePlugin can do this.

  • Cross-env can inject variables globally, systemically, and the following command will inject DEV into the env environment variable
Cross-env env =DEV webpack-dev-server --inline --hot --quiet --progress --content-base pages/ HTML --host 0.0.0.0 --port 8888Copy the code
  • DefinePlugin willprocess.env.ENVThis environment variable is injectedENV
new webpack.DefinePlugin({
    'ENV': JSON.stringify(process.env.ENV)
})
  • inmain.jsYou can distinguish between a development environment and a production environment:
if(ENV == 'DEV') {
    require('pages/html/page1.html')    
}

ES2015 && Babel

If you want to configure the ES2015 development environment in Webpack, you need Babel’s help:

  • babel-core
  • babel-loader
  • babel-preset-es2015
  • babel-preset-stage-0
  • babel-plugin-add-module-exports
  • babel-plugin-transform-runtime
cd 4_es2015
npm install
npm run dev

Then in webpack.config.js:

{
    test: /\.js$/,
    loader: "babel",
    exclude: /node_modules/
}

Exclude: /node_modules/ is important, otherwise Babel may compile all modules in node_modules using Babel!

Also, create a new.babelrc directory under the root directory:

{
    presets: [
        "es2015",
        "stage-0"
    ],
    plugins: [
        "transform-runtime",
        "add-module-exports"
    ]   
}

Then we can write our lovely ES2015:

import './style.css' import { log } from '.. /common/index.js'

Five, into the storage

cd 5_library
npm install
npm run dev

CommonsChunkPlugin

CommonsChunkPlugin is a plugin that comes with Webpack and extracts public modules:

plugins: [
    new webpack.optimize.CommonsChunkPlugin('common','common.js') 
]

By adding the common/index.js module to HtmlWebpackPlugin, we can see that the common/index.js module is extracted into common.js. Otherwise, common/index.js is packaged in both page1/main and page2/main.

externals

In actual development, we will also use

JQuery externals: {jQuery: 'window.jquery'}

Then we can use jQuery in page1/main.js:

import $ from 'jQuery'
$('body')
    .append('<p>this is jQuery render</p>')
    .css('color', '#FFF')

ProvidePlugin

Of course, for a library like jQuery that is used on every page, it would be inelegant to import $from ‘jQuery’ every time. It can be configured like this:

plugins: [
    new webpack.ProvidePlugin({
        $: 'jquery'
    })
]

This can be done as in page2/main.js:

$('body')
    .append('<p>this is jQuery render</p>')
    .css('color', '#3f3f3f')

Six, agents,

After the above steps, we have basically completed the development environment of WebPack, but pages is full of static pages, and our back end may actually use PHP, Python, or even Node render dynamic pages.

Now we need to solve the problem of combining the existing WebPack development environment with the existing backend environment, we use webpack-dev-server proxy function:

devServer: {
    proxy: {
        '*': {
            target: 'http://localhost:8000'
        }
    }
}
cd 6_proxy
npm install
npm run dev

To simulate a back-end environment, use PHP’s own server to start the service on port 8000:

PHP -s 127.0.0.1:8000-t./pages/ HTML

Then open the http://0.0.0.0:8888/page1.php you will see a page is webpack dev – server agent. You can get a formal page with resource paths configured under Pages/HTML.

After executing NPM run build, you will get the resource path of the corresponding CDN address under Pages/HTML. The CDN address can be configured under NPM scripts:

"scripts": {
    "build": "cross-env CDN=http://cdn.a.com webpack"
}

7. Teamwork

At this point, a webPack-built multi-page development environment is complete, and there are a few non-WebPack-related topics to note.

ESLint

ESLint is a code checking tool that I won’t cover here. If you’re using ES2015, just install babel-esLint.

pre-commit

Pre-commit is a great tool that you can use to force team members to execute any command (ESLint, tests, etc.) before committing code.

"scripts": {
    "lint": "eslint app/src/ app/stylesheets"
},
"precommit": [ "lint" ]

Note to install before use:

node node_modules/pre-commit/install.js

8. A scaffold template

I also set up the project github.com/fe-config/g… , it includes the most basic Webpack development multi-page skeleton, interested can also have a look. Since it’s a mapping between map.js and template files, this idea should save you a lot of code.

Most importantly, get started with WebPack!

I hope this tutorial helped you


Donations to me | about me