English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
After learning the top-level tutorial of webpack, I think it may be specially tailored for single-page applications, such as webpack+react, webpack+vue, etc., can solve various resource dependency loading and packaging problems. Even css is packaged in js and dynamically added to the dom document.
If we want to create a multi-page ordinary web site, css is extracted out, and js needs to be loaded as modules?
Project address:webpackDemo_jb51.rar
Initialize project, install dependencies
package.json
"devDependencies": { "css-loader": "^0.23.1", "extract-text-webpack-plugin": "^1.0.1", "file-loader": "^0.8.5", "html-loader": "^0.4.3", "html-webpack-plugin": "^2.9.0", "jquery": "^1.12.0", "less": "^2.6.0", "less-loader": "^2.2.2", "sass-loader": "^4.0.2", "style-loader": "^0.13.0", "url-loader": "^0.5.7", "webpack": "^1.12.13", "webpack-dev-server": "^1.14.1" }
Directory structure (I use the express framework, others according to personal needs)
- webpackDemo - src #Code development directory - css #CSS directory, organized at three levels: page (module), general, and third-party + page + common + lib - js #JS scripts, organized according to page, components + page + components + template #HTML template - node_modules #Used nodejs modules - public #Express static resource files - dist #Output directory of webpack compilation and packaging, no need to create directory, it can be automatically generated by webpack according to the configuration + css + js + img #Image resources + view #Express static resource files (compiled and packaged output directory of webpack to view directory) package.json #Project configuration webpack.config.js #webpack configuration
Developing pages
In src/js/Establish an index.js file under the page directory, in the src/Establish an index.html file under the view directory. The entry JS and template file names correspond.
index.html content is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Home</title> !-- Description: No need to introduce CSS and facicon in the head, webpack will automatically implement on-demand loading or generate style tags according to the requirements of the entry JS file --> </head> <body> !-- Description: No need to introduce JS files separately in the body, webpack will automatically implement on-demand loading or generate script tags according to the entry JS file, and can also generate corresponding hash values --> </body> </html>
It is just such a simple HTML template, do not introduce any CSS and JS, and it can automatically help us introduce through webpack packaging
index.js content is as follows:
//Introduce css require("../../css/lib/base.css"); require("../../css/page/index.scss"); $('body').append('<p class="text">index</p>');
page1.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>page1</title> </head> <body> </body> </html>
page1.js:
//Introduce css require("../../css/lib/base.css"); require("../../css/page/page1.less"); $('body').html('page1');
Webpack configuration (I use the express framework, others according to personal needs)
var path = require('path'); var webpack = require('webpack'); /* extract-text-webpack-plugin plugin, With it, you can extract your styles into separate css files, Mom no longer needs to worry that styles will be packaged into js files. */ var ExtractTextPlugin = require('extract-text-webpack-plugin'); /* html-webpack-plugin plugin, a very important plugin, a plugin for generating HTML in webpack, Specifically, you can check here https://www.npmjs.com/package/html-webpack-plugin */ var HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { //Configure the entry file, write as many as there are index: './src/js/page/index.js', page1: './src/js/page/page1.js' }, output: { path: path.join(__dirname, './public/dist/'), //Configuration of the output directory, the path configuration of templates, styles, scripts, images, and other resources are relative to it publicPath: '/dist/', //The path on the server for templates, styles, scripts, images, and other resources filename: 'js/[name].js', //Configuration for the main JS file corresponding to each page chunkFilename: 'js/[id].chunk.js' //Chunk generation configuration }, module: { loaders: [ //Loaders, for the parameter configuration of each loader, you can search it yourself. { test: /.css$/, //Configure the css extractor and loader.-loader' can be omitted loader: ExtractTextPlugin.extract('style-loader', 'css-loader) test: /.less$/, //Configure the less extractor and loader. It is necessary to explain the middle! //Invoke the less and css loaders in the order from right to left, with the output of the previous one as the input of the next one //You can also develop your own loader. For the syntax of loader, you can google it yourself. loader: ExtractTextPlugin.extract('css!less') test: /\.scss$/, //Configure the scss extractor and loader. It is necessary to explain the middle! //Invoke the scss and css loaders in the order from right to left, with the output of the previous one as the input of the next one //You can also develop your own loader. For the syntax of loader, you can google it yourself. loader: ExtractTextPlugin.extract('css!scss') //HTML template loader, which can handle referenced static resources, with default configuration parameter attrs=img:src, processing the src reference of images //For example, if you configure, attrs=img:src img:data-src can be processed together with data-src refers to the resources, as shown below test: /.html$/, loader: "html?attrs=img:src img:data-src" //File loader, handles static file resources test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader?name=./fonts/[name].[ext] //Image loader, similar to file-loader, more suitable for images, can convert smaller images to base64to reduce http requests //bytes to base8192Convert images smaller than64Code test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=8192&name=./img/[hash].[ext]' } ]), }, plugins: [ new webpack.ProvidePlugin({ //Load jq $: 'jquery' }), new webpack.optimize.CommonsChunkPlugin({ name: 'commons', // Extract the common modules and generate a chunk named 'commons' chunks: ['index','page1'], //Extract common parts of which modules minChunks: 2 // Extract at least2Common parts of modules }), new ExtractTextPlugin('css/[name].css'), //Load css using link tag separately and set the path, relative to publickPath in output configuration //HtmlWebpackPlugin, configuration related to template generation, each for the configuration of a page, write as many as there are new HtmlWebpackPlugin({ //Insert css according to the template/js and other files generate the final HTML favicon: '.',/src/favicon.ico', //favicon path, introduced through webpack and can generate hash value filename: '../../views/index.html', //The path where the generated html is stored, relative to path template: '.',/src/template/index.html', //html template path inject: 'body', //js insertion position, true/'head'/'body'/false hash: true, //Generate hash values for static resources chunks: ['commons', 'index'],//Chunks that need to be imported, if not configured, all resources of the pages will be imported minify: { //Compress HTML file removeComments: true, //Remove comments from HTML collapseWhitespace: false //Delete whitespace and newline characters } }), new HtmlWebpackPlugin({ //Insert css according to the template/js and other files generate the final HTML favicon: '.',/src/favicon.ico', //favicon path, introduced through webpack and can generate hash value filename: '../../views/page1.html', //The path where the generated html is stored, relative to path template: '.',/src/template/page1.html', //html template path inject: true, //js insertion position, true/'head'/'body'/false hash: true, //Generate hash values for static resources chunks: ['commons', 'list'],//Chunks that need to be imported, if not configured, all resources of the pages will be imported minify: { //Compress HTML file removeComments: true, //Remove comments from HTML collapseWhitespace: false //Delete whitespace and newline characters } } // new webpack.HotModuleReplacementPlugin(), //Hot loading ], //Use webpack-dev-server, to improve development efficiency // devServer: { // contentBase: '.',/', // host: 'localhost', // port: 9090, //Default8080 // inline: true, //Can monitor js changes // hot: true, //Hot restart // } };
After completing the above configurations, execute the webpack packaging command to complete the project packaging.
Hash: e6219853995506fd132a Version: webpack 1.14.0 Time: 1338ms Asset Size Chunks Chunk Names js/index.js 457 bytes 0 [emitted] index js/page1.js 392 bytes 1 [emitted] page1 js/commons.js 306 kB 2 [emitted] commons css/index.css 62 bytes 0 [emitted] index css/page1.css 62 bytes 1 [emitted] page1 css/commons.css 803 bytes 2 [emitted] commons favicon.ico 1.15 kB [emitted] ../../view/index.html 496 bytes [emitted] ../../view/page1.html 499 bytes [emitted] [0] ./src/js/page/index.js 170 bytes {0} [built] [0] ./src/js/page/page1.js 106 bytes {1} [built] + 7 hidden modules Child html-webpack-plugin for "../../view/page1.html": + 1 hidden modules Child html-webpack-plugin for "../../view/index.html": + 1 hidden modules Child extract-text-webpack-plugin: + 2 hidden modules Child extract-text-webpack-plugin: + 2 hidden modules Child extract-text-webpack-plugin: + 2 hidden modules
At this time, go to the views directory to view the generated index.html file, as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Home</title> <link rel="shortcut icon" href="/dist/favicon.ico" rel="external nofollow" ><link href="/dist/css/commons.css?e6219853995506fd132a" rel="external nofollow" rel="stylesheet"><link href="/dist/css/index.css?e6219853995506fd132a" rel="external nofollow" rel="stylesheet"></head> <body> <script type="text/javascript" src="/dist/js/commons.js?e6219853995506fd132a"></script><script type="text/javascript" src="/dist/js/index.js?e6219853995506fd132a"></script></body> </html>
As can be seen, the generated files, in addition to retaining the content of the original template, also automatically add the necessary CSS and JS files, as well as favicon, and also add the corresponding hash values.
Two questions
var path = require('path'); var webpack = require('webpack'); var glob = require('glob'); /* extract-text-webpack-plugin plugin, With it, you can extract your styles into separate css files, Mom no longer needs to worry that styles will be packaged into js files. */ var ExtractTextPlugin = require('extract-text-webpack-plugin'); /* html-webpack-plugin plugin, a very important plugin, a plugin for generating HTML in webpack, Specifically, you can check here https://www.npmjs.com/package/html-webpack-plugin */ var HtmlWebpackPlugin = require('html-webpack-plugin'); /** *Extract the common modules and generate a chunk named 'commons' */ var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; //Compression var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; //Determine development mode var debug = process.env.NODE_ENV !== 'production'; var getEntry = function(globPath, pathDir) { var files = glob.sync(globPath); var entries = {}, entry, dirname, basename, pathname, extname; for (var i = 0; i < files.length; i++) { entry = files[i]; dirname = path.dirname(entry); //File directory extname = path.extname(entry); //Suffix name basename = path.basename(entry, extname); //Filename pathname = path.join(dirname, basename); pathname = pathDir ? pathname.replace(new RegExp('^' + pathDir), '') : pathname; entries[pathname] = ['./' + entry]; //This is written under the osx system, win7 entries[basename] } console.log(entries); return entries; } //Entry (all page entry files obtained through the getEntry method) var entries = getEntry('src/js/page/**/*.js', 'src/js/page/'); //Extract which modules have common parts from the entries to obtain file names var chunks = Object.keys(entries); //Template pages (all template pages obtained through the getEntry method) var pages = Object.keys(getEntry('src/template/**/*.html', 'src/template/')); console.log(pages) var config = { entry: entries, output: { path: path.join(__dirname, './public/dist/'),//Configuration of the output directory, the path configuration of templates, styles, scripts, images, and other resources are relative to it publicPath: '/dist/', //The path on the server for templates, styles, scripts, images, and other resources filename: 'js/[name].js', //Configuration for the main JS file corresponding to each page chunkFilename: 'js/[id].chunk.js?[chunkhash]' //Chunk generation configuration }, module: { loaders: [ //Loader { test: /.css$/, loader: ExtractTextPlugin.extract('style', 'css') test: /.less$/, loader: ExtractTextPlugin.extract('css!less') test: /.html$/, loader: "html?-minimize" //Avoid HTML compression, https://github.com/webpack/html-loader/issues/50 test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader?name=fonts/[name].[ext] test: /\.(png|jpe?g|gif)$/, loader: 'url-loader?limit=8192&name=imgs/[name]-[hash].[ext]' } ]), }, plugins: [ new webpack.ProvidePlugin({ //Load jq $: 'jquery' }), new CommonsChunkPlugin({ name: 'commons', // Extract the common modules and generate a chunk named 'commons' chunks: chunks, minChunks: chunks.length // Extract all modules that are commonly dependent on all entries }), new ExtractTextPlugin('css/[name].css'), //Load css using link tag separately and set the path, relative to publickPath in output configuration debug ? function() {} : new UglifyJsPlugin({ //Compress code compress: { warnings: false }, except: ['$super', '$', 'exports', 'require'] //Exclude keywords }), ]), }; pages.forEach(function(pathname) { var conf = { filename: '../../views/' + pathname + '.html', //The path where the generated html is stored, relative to path template: 'src/template/' + pathname + '.html', //html template path inject: false, //js insertion position, true/'head'/'body'/false /* * For compression, html-minify will cause many html syntax check issues during compression * If you use {{...}} expressions on html tag attributes, so in many cases it is not necessary to configure the compression item here * Additionally, UglifyJsPlugin will compress html along with the code when compressing. * To avoid compressing html, you need to configure it in html-Loader configuration 'html?-minimize', see html in loaders-Loader configuration. */ // minify: { //Compress HTML file // removeComments: true, //Remove comments from HTML // collapseWhitespace: false //Delete whitespace and newline characters // } }; if (pathname in config.entry) { favicon: '.',/src/favicon.ico', //favicon path, introduced through webpack and can generate hash value conf.inject = 'body'; conf.chunks = ['commons', pathname]; conf.hash = true; } config.plugins.push(new HtmlWebpackPlugin(conf)); }); module.exports = config;
The following code is similar to the above, the essential difference is that all related files are put into an object through a method, thus completing the automatic import effect!
The above are all configurations on the mac osx system, win7The path may be different
glob: The parsed results here are different:
but ultimately
entries: { index: ['./src/template/index.js'], page1: ['./src/template/page1.js'] } pages: 'index', 'page1']
It should be changed according to the configuration of your personal computer
That's all for this article, I hope it will be helpful to everyone's learning, and I also hope everyone will support Yell Tutorial more.
Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been edited by humans, and does not assume relevant legal liability. If you find content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @ when sending email) and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.