Front-end engineering environment built with Webpack

Source: Internet
Author: User

With the release of webpack3.x, its functions are becoming more and more powerful, and many of the project's compiling and packaging tools are gradually transferred from gulp to Webpack. Recently, because of the project refactoring to consider using Vue, but also want to switch from the original gulp to Webpack, so set up the webpack-vue of the front-end scaffolding tools, here to record the main points in the process of construction. Project Source

1. Use yarn instead of NPM

NPM is a very good package management tool, which is always dependent on the NPM installation project because some of the dependencies of the new version of the package will lead to a different compilation result, because NPM does not lock the dependent package version number when installing dependencies (NPM5 seems to have solved the problem), Each time you install, you always get the latest dependent packages, which results in a different compilation result. Using yarn to install a dependency package can solve this problem perfectly.
Go to the official website to download and install yarn
Execute yarn-versions on the command line, if output version number indicates successful installation

2. Initializing the build Package.json file

Perform yarn init and fill out project-related information

3. Installing project Dependencies and developing dependency packages

Perform yarn Add * * *, install Project dependency package, add--dev to install as development dependency, install dependent package can consult project source Package.json file

4. Build a common library profile and package common library files 1. New Webpack-dll.config.js File

As long as this configuration file is used to package the library files, here are the next few key configuration

output:{    path: outputDir,    filename:'js/lib/[name].js',    library:'[name]_library',    /*libraryTarget: 'umd'*/},

The library and Librarytarget in output are designed to customize how the packaged files are exported, using the default var form

newwebpack.DefinePlugin({    'process.env':{        NODE_ENV:JSON.stringify('production')    }}),

This defines the environment as a development environment and facilitates the creation of library files directly for the development environment

 //stability module ID  new  webpack . hashedmoduleidsplugin  ()  new  webpack . dllplugin  ({ //the index of modules in this DLL file for Dllreferenceplugin read use  path  :  dll_manifest_name +    //all the contents of the current DLL will be placed under a global variable with the variable name specified in this parameter, note that the parameter output.library is consistent  name  :   "[Name]_library '    //specifies a path as the context and needs to be consistent with the Dllreferenceplugin's context parameter, and is recommended to be set to the project root directory uniformly  context  :  __dirname } ) 

This is to stabilize the module ID and generate the manifest file, making it easy to read dll_manifest in the production environment to know which files have been packaged by the DLL without having to pack again

2. Create a library file Dll.js

The yarn DLL is executed and the Dll.js file is generated under the src/app/js/lib/folder, which is packaged with Vue2.5.13,axios0.17.1,flexible,webpack-zepto, Specifically which files to package can be configured by the entries in Webpack-dll.config.js
Consider generating dll.css if necessary

5. Create a configuration file

Here I will divide the configuration file into 3, a basic configuration file, a development environment profile, a production environment profile, a development environment and a production environment configuration file through the Webpack-merge plug-in call the underlying configuration file.

Basic configuration File Webpack.base.js

Basic configuration information is included in the basic configuration file, which mainly describes the use of the Htmlwebpackplugin plugin in the next multi-page configuration.

varPages= Getentry(Entrydir+ '/html/**/*.ejs '); for(varPathnameinchPages){    varConf= {        //HTML template file input path        Template:Entrydir+ '/html/' +Pathname+ '. js ',        //HTML file output path        filename:OutputDir+ '/html/' +Pathname+ '. html ',        Inject: true,        Cache: true, //change-only documents        minify: {            removecomments: true,            Collapsewhitespace: false        }    };    //Extract page js,css and public verdors according to chunks    if(Pathnameinch Module.exports.entry){        conf.chunks =[Pathname, ' Vendors '];    } Else {        conf.chunks =[' Vendors '];    }    Module.exports.Plugins.Push(New Htmlwebpackplugin(conf));}

Here the Multi-page configuration is Ejs template, through the loop entry file, each template file is configured a Htmlwebpackplugin plug-in compilation, and finally achieve the purpose of generating multiple pages, through chunks to extract the page js/css/img, etc.

Development environment configuration file Webpack.dev.js

Create a static server service by using the Webpack-dev-server plugin in the development environment configuration file

Devserver: {    //Set Server home folder, by default, provide files from the root directory of the project    Contentbase:OutputDir,    //Automatically open default browser    //open:true,    //Turn on Hot module replacement and reload only the changed parts of the page    //hot:true,    //hotonly:true,    //Turn on gzip compression    Compress: true,    //using Inlilne mode, the dynamic reload of the page is triggered    inline: true,    //When compiling an error, an error message is displayed on the webpage    Overlay: {        Warnings: true,        Errors: true    },    //The folder that the browser automatically opens    //openpage: ' html/',    //Display error messages only in the shell    //stats: ' Errors-only ',    //Set domain name, default is localhost    Host: ' localhost ',    Port: 8080},

Need to use Hot update plug-in when using hot update

//热模块替换插件newwebpack.HotModuleReplacementPlugin()
Production environment configuration file Webpack.prod.js

In a production environment, we need to focus on the separation of public components, code compression, file caching, and so on when public components are detached by reading the Dll_manifest file to know which files are not packaged, thereby reducing the size of the packaged file

New Webpack.Hashedmoduleidsplugin(),New Webpack.Dllreferenceplugin({    //Specify a path as the context, which needs to be consistent with the Dllplugin context parameter, it is recommended to set the project root directory uniformly    Context:__dirname,    //Specify Manifest.json    Manifest: require('.. /' +Dll_manifest_name+ '. JSON '),    all contents of the current DLL will be stored under a global variable with the variable name specified in this parameter, note that the name parameter of the Dllplugin is consistent with the    name: ' Dll_library ',}),

When considering code compression, use the following configuration

//Compress CSS codeNew Optimizecssassetsplugin({    Assetnameregexp: /\.CSS\.*(?!.*Map)/g, //Be careful not to write/\.css$/g    Cssprocessor: require(' Cssnano '),    cssprocessoroptions: {        discardcomments: { RemoveAll: true },        //Avoid Cssnano recalculation Z-index        Safe: true    },    Canprint: true}),//Extract CSSNew Extracttextplugin(' css/[name].css?v=[contenthash:8] '),//Compression JS codeNew Webpack.optimize.Uglifyjsplugin({    Compress: {        Warnings: false    },    Output: {        Comments: false,    }}),

You can use the following configuration when considering online file caching issues

output:{    //publicPath: 'http://localhost:8080/',    filename:'js/[name].js?v=[chunkhash:8]'},

It is recommended to use Chunkhash, and each compilation will change with hash

At this point the configuration is basically complete, there are still some shortcomings, has been improving. SOURCE src/app/folder has a demo, you can refer to the demo happy to develop, there are questions welcome comments proposed

Reference documents
    1. Webpack official documentation,
    2. Webpack's DLL function,
    3. The difference between hash, Chunkhash and Contenthash in the detailed Webpack

Front-end engineering environment built with Webpack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.