Table of Contents
Introduction
Directory
Configuration
Multiple entries
module
View View
plugins
Development
Build
Home Web Front-end HTML Tutorial Multi-entry project scaffolding implemented by webpack

Multi-entry project scaffolding implemented by webpack

Jun 27, 2017 am 09:06 AM
web webpack Entrance accomplish scaffold project

Introduction

A multi-entry project scaffolding based on webpack2, mainly using extract-text-webpack-plugin to implement js and css public code extraction, html-webpack-plugin to implement html multi-entry, and less-loader to implement less compiles, postcss-loader configures autoprefixer to automatically add browser-compatible prefixes, html-withimg-loader implements adding image version numbers and template functions into HTML, babel-loader implements ES6 transcoding function, and happypack multi-threading accelerates the construction speed.

Directory

├── dist                     # 构建后的目录
├── config                   # 项目配置文件
│   ├── webpack.config.js    # webpack 配置文件
│   └── postcss.config.js    # postcss 配置文件
├── src                      # 程序源文件
│   └── js                   # 入口
│   ├   └── index.js         # 匹配 view/index.html
│   ├   └── user         
│   ├   ├    ├── index.js    # 匹配 view/user/index.html
│   ├   ├    ├── list.js     # 匹配 view/user/list.html
│   ├   └── lib              # JS 库等,不参与路由匹配
│   ├       ├── jquery.js 
│   └── view                 
│   ├    └── index.html       # 对应 js/index.js
│   ├    └── user         
│   ├        ├── index.html   # 对应 js/user/index.js
│   ├        ├── list.html    # 对应 js/user/list.js
│   └── css                   # css 文件目录
│   ├    └── base.css          
│   ├    └── iconfont.css     
│   └── font                  # iconfont 文件目录
│   ├    └── iconfont.ttf         
│   ├    └── iconfont.css
│   └── img                   # 图片文件目录
│   ├    └── pic1.jpg         
│   ├    └── pic2.png     
│   └── template              # html 模板目录
│       └── head.html         
│       └── foot.html
Copy after login

Configuration

Multiple entries

Get the multi-entry array according to the JS directory

const ROOT = process.cwd();  // 根目录

let entryJs = getEntry('./src/js/**/*.js');

/**
 * 根据目录获取入口
 * @param  {[type]} globPath [description]
 * @return {[type]}          [description]
 */
function getEntry (globPath) {
    let entries = {};
    Glob.sync(globPath).forEach(function (entry) {
        let basename = path.basename(entry, path.extname(entry)),
            pathname = path.dirname(entry);
        // js/lib/*.js 不作为入口
        if (!entry.match(/\/js\/lib\//)) {
            entries[pathname.split('/').splice(3).join('/') + '/' + basename] = pathname + '/' + basename;
        }
    });
    return entries;
}

// webpack 配置
const config = {
    entry: entryJs,
    output: {
        filename: 'js/[name].js?[chunkhash:8]',
        chunkFilename: 'js/[name].js?[chunkhash:8]',
        path: path.resolve(ROOT, 'dist'),
        publicPath: '/'
    },  
}
Copy after login

module

Use babel to implement ES2015 to ES5, less to css and use postcss to implement autoprefixer to automatically add browser compatibility, url-loader to implement css to reference images and fonts and add version numbers, html -withimg-loader implements html reference images, adds version numbers and implements template functions.

module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
                loader: 'babel-loader?id=js',
                options: {
                    presets: ['env']
                }
            }
        },
        {
            test: /\.(less|css)$/,
            use: ExtractTextPlugin.extract({
                fallback: 'style-loader?id=styles',
                use: [{
                        loader: 'css-loader?id=styles',
                        options: {
                            minimize:  !IsDev
                        }
                    }, 
                    {
                        loader: 'less-loader?id=styles'
                    }, 
                    {
                        loader: 'postcss-loader?id=styles',
                        options: {
                            config: {
                                path: PostcssConfigPath
                            }
                        }
                    }
                ]
            })
        },
        {
            test: /\.(png|jpg|gif)$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 100,
                        publicPath: '',
                        name: '/img/[name].[ext]?[hash:8]'
                    }
                }
            ]
        },
        {
            test: /\.(eot|svg|ttf|woff)$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 100,
                        publicPath: '',
                        name: '/font/[name].[ext]?[hash:8]'
                    }
                }
            ]
        },
        // @see 
        {
            test: /\.(htm|html)$/i,
            loader: 'html-withimg-loader?min=false'
        }
    ]
},


// postcss.config.js
module.exports = {
    plugins: [
        require('autoprefixer')({
            browsers: ['> 1%', 'last 5 versions', 'not ie <= 9'],
        })
    ]
}
Copy after login

View View

According to the directory correspondence, obtain the html entry corresponding to js

let entryHtml = getEntryHtml('./src/view/**/*.html'),
    configPlugins;

entryHtml.forEach(function (v) {
    configPlugins.push(new HtmlWebpackPlugin(v));
});

// webpack 配置
resolve: {
    alias: {
        views:  path.resolve(ROOT, './src/view')    
    }
},

/**
 * 根据目录获取 Html 入口
 * @param  {[type]} globPath [description]
 * @return {[type]}          [description]
 */
function getEntryHtml (globPath) {
    let entries = [];
    Glob.sync(globPath).forEach(function (entry) {
        let basename = path.basename(entry, path.extname(entry)),
            pathname = path.dirname(entry),
            // @see 
            minifyConfig = IsDev ? '' : {
                removeComments: true,
                collapseWhitespace: true,
                minifyCSS: true,
                minifyJS: true  
            };

        entries.push({
            filename: entry.split('/').splice(2).join('/'),
            template: entry,
            chunks: ['common', pathname.split('/').splice(3).join('/') + '/' + basename],
            minify: minifyConfig
        });

    });
    return entries;
}
Copy after login

plugins

Use happypack multi-threading to speed up the build, CommonsChunkPlugin implements extraction of public js into separate files, extract-text-webpack-plugin implements extraction of public css into separate files,

let configPlugins = [
    new HappyPack({
        id: 'js',
        // @see 
        threadPool: HappyThreadPool,
        loaders: ['babel-loader']
    }),
    new HappyPack({
        id: 'styles',
        threadPool: HappyThreadPool,
        loaders: ['style-loader', 'css-loader', 'less-loader', 'postcss-loader']
    }),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'common'
    }),
    // @see 
    new ExtractTextPlugin({
        filename: 'css/[name].css?[contenthash:8]',
        allChunks: true
    })
];

entryHtml.forEach(function (v) {
    configPlugins.push(new HtmlWebpackPlugin(v));
});

// webpack 配置
plugins: configPlugins,
Copy after login

Development

webpack-dev-server implements functions such as automatic refresh of the development environment

// webpack 配置
devServer: {
    contentBase: [
        path.join(ROOT, 'src/')
    ],
    hot: false,
    host: '0.0.0.0',
    port: 8080
}
Copy after login

Development

npm start
Copy after login

http://localhost:8080/view

Build

cross-env realizes the distinction between development and production environment build

Development environment build, no code compressionProduction environment build, compressed code
Command Description
##npm run dev
npm run build
Warehouse

Welcome star


Please indicate the source for reprinting:

The above is the detailed content of Multi-entry project scaffolding implemented by webpack. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can AI conquer Fermat's last theorem? Mathematician gave up 5 years of his career to turn 100 pages of proof into code Can AI conquer Fermat's last theorem? Mathematician gave up 5 years of his career to turn 100 pages of proof into code Apr 09, 2024 pm 03:20 PM

Fermat's last theorem, about to be conquered by AI? And the most meaningful part of the whole thing is that Fermat’s Last Theorem, which AI is about to solve, is precisely to prove that AI is useless. Once upon a time, mathematics belonged to the realm of pure human intelligence; now, this territory is being deciphered and trampled by advanced algorithms. Image Fermat's Last Theorem is a "notorious" puzzle that has puzzled mathematicians for centuries. It was proven in 1993, and now mathematicians have a big plan: to recreate the proof using computers. They hope that any logical errors in this version of the proof can be checked by a computer. Project address: https://github.com/riccardobrasca/flt

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

A closer look at PyCharm: a quick way to delete projects A closer look at PyCharm: a quick way to delete projects Feb 26, 2024 pm 04:21 PM

Title: Learn more about PyCharm: An efficient way to delete projects. In recent years, Python, as a powerful and flexible programming language, has been favored by more and more developers. In the development of Python projects, it is crucial to choose an efficient integrated development environment. As a powerful integrated development environment, PyCharm provides Python developers with many convenient functions and tools, including deleting project directories quickly and efficiently. The following will focus on how to use delete in PyCharm

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

What is the entrance URL of Manwa Comics? What is the entrance URL of Manwa Comics? Feb 27, 2024 pm 06:58 PM

Manwa Comics is a comic reading platform. It has a lot of wonderful comic resources recommended to everyone. Everyone can watch them according to their own preferences. However, many users have never been able to find the entrance URL of Manwa Comics. So this book Below, the site editor will share with you the entrance to Frog Comics, so that you can better find the comics you like! I hope it can help everyone in need. Frog Comics entrance: https://fuw11.cc/mw666 Frog Comics is currently closed. What I share with you is the official entrance of Manwa Comics. Manwa Comics is also a comics reading platform. Here you can see many types of comics, including Japanese comics, Korean comics, European and American comics and other resources that you are interested in. All of them are free resources.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

See all articles