Webpack Common Function Introduction

Source: Internet
Author: User
Tags html style tag
<span id="Label3"></p>Webpack Overview of common functions<p><p>Webpack is a tool for users to package front-end Modules. Primarily used to package JavaScript used on the browser side. It can also convert, bundle, and package other static resources, including css, image, font file, template, and so On. Personally think its advantage is easy to use, and commonly used functions are basically, in addition, you can develop loader and plugin to meet their own needs. Here is as far as possible in detail to introduce the use of some basic functions.</p></p>Installation<pre><pre> <code></code></pre></pre>Run Webpack<p><p>Webpack need to write a config file, and then follow this file to perform the required packaging functions. Let's write one of the simplest config now. Create a new file named Webpack-config.js. The config file is actually a commonjs module. The contents are as Follows:</p></p><pre><pre> <code>var webpack = require(‘webpack‘);var path = require(‘path‘);var buildPath = path.resolve(__dirname,"build");var nodemodulesPath = path.resolve(__dirname,‘node_modules‘);var config = { //入口文件配置 entry:path.resolve(__dirname,‘src/main.js‘), resolve:{ extentions:["","js"]//当requrie的模块找不到时,添加这些后缀 }, //文件导出的配置 output:{ path:buildPath, filename:"app.js" }}module.exports = config;</code></pre></pre><p><p>The structure of my directory is this:</p></p><pre><pre> <code>webpack |---index.html |---webpack-config.js |---src |---main.js |---js |---a.js</code></pre></pre><p><p>The contents of the Main.js file are as Follows:</p></p><pre><pre> <code>var a = require(‘./js/a‘);a();console.log(‘hello world‘);document.getElementById("container").innerHTML = "<p>hello world</p>";</code></pre></pre><p><p>The contents of the A.js file are as Follows:</p></p><pre><pre> <code>module.exports = function(){ console.log(‘it is a ‘);}</code></pre></pre><p><p>Then we execute the following command:</p></p><pre><pre> <code>webpack --config webpack-config.js --colors</code></pre></pre><p><p>So that we can see in the directory a newly generated directory build, the directory structure is as Follows:</p></p><pre><pre> <code>webpack |---index.html |---webpack-config.js |---build |---app.js</code></pre></pre><p><p>Then quoting App.js is Ok. The contents of the Main.js and module a.js are packaged in App.js. This demonstrates the simplest way to package JS from a module to a file.</p></p>Introducing the Webpack config file<p><p>Webpack is a project that is packaged according to the content described in Config. Then let's explain what the nodes in the config file mean respectively. A config file, which is basically made up of the following configuration Items.</p></p> <ul> <ul> <li><p>Entry</p></li> </ul> </ul><p><p>Configure the portal for the files to be packaged; You can configure multiple entry files, as described below.</p></p> <ul> <ul> <li><p>Resolve</p><p>configuration file suffix name, In addition to js, there are jsx, coffee and so On. In addition to this feature can also configure other useful features, as I still do not fully understand, have known friends welcome advice.</p></li> <li><p>Output</p><p>Configure the output file path, file name, and so On.</p></li> <li><p>Module (loaders)</p></li> </ul> </ul><p><p>Configure the loader to be Used. Perform some appropriate processing of the File. For example, Babel-loader can convert es6 files into es5.<br>Most of the functions of file processing are implemented through Loader. Loader is the equivalent of a task in Gulp. Loader can be used to process files that are require and otherwise referenced in the portal File. Loader is typically a standalone node module, which is installed Separately.</p></p><p><p>Loader configuration Items:</p></p><pre><pre> <code> test: /\.(js|jsx)$/,//注意是正则表达式,不要加引号,匹配要处理的文件 loader: ‘eslint-loader‘,//要使用的loader,"-loader"可以省略 include: [path.resolve(__dirname, "src/app")],//把要处理的目录包括进来 exclude: [nodeModulesPath]//排除不处理的目录</code></pre></pre><p><p>Current list of Loader:<br>Https://webpack.github.io/docs/list-of-loaders.html</p></p><p><p>An example of a module:</p></p><pre><pre> <code>module: { preLoaders: [ { test: /\.(js|jsx)$/, loader: ‘eslint-loader‘, include: [path.resolve(__dirname, "src/app")], exclude: [nodeModulesPath] }, ], loaders: [ { test: /\.(js|jsx)$/, //正则表达式匹配 .js 和 .jsx 文件 loader: ‘babel-loader?optional=runtime&stage=0‘,//对匹配的文件进行处理的loader exclude: [nodeModulesPath]//排除node module中的文件 } ]}</code></pre></pre> <ul> <ul> <li><p>Plugins</p><p>As the name implies, Configure the plug-in you want to Use. But there is no difference between plugin and loader to be studied.</p></li> </ul> </ul><p><p>Take a look at an example using Plugin:</p></p><pre><pre> <code>plugins: [ //压缩打包的文件 new webpack.optimize.UglifyJsPlugin({ compress: { //supresses warnings, usually from module minification warnings: false } }), //允许错误不打断程序 new webpack.NoErrorsPlugin(), //把指定文件夹xia的文件复制到指定的目录 new TransferWebpackPlugin([ {from: ‘www‘} ], path.resolve(__dirname,"src")) ]</code></pre></pre><p><p>Current list of plugins:<br>Http://webpack.github.io/docs/list-of-plugins.html</p></p>How to compress the output file<pre><pre> <code>plugins: [ //压缩打包的文件 new webpack.optimize.UglifyJsPlugin({ compress: { //supresses warnings, usually from module minification warnings: false } })]</code></pre></pre>How to copy files from directory to output directory<p><p>The copy file needs to be completed by the plugin "transfer-webpack-plugin".</p></p><p><p>Installation:</p></p><pre><pre> <code>npm install transfer-webpack-plugin -save</code></pre></pre><p><p>Configuration:</p></p><pre><pre> <code>var TransferWebpackPlugin = require(‘transfer-webpack-plugin‘);//其他节点省略 plugins: [ //把指定文件夹下的文件复制到指定的目录 new TransferWebpackPlugin([ {from: ‘www‘} ], path.resolve(__dirname,"src")) ]</code></pre></pre>Packaging JavaScript Modules<p><p>The supported JS Modular Solutions Include:</p></p> <ul> <ul> <li><p>ES6 Module</p><p>Import MyModule from './mymodule.js ';</p></li> <li><p>CommonJS</p><p>var mymodule = require ('./mymodule.js ');</p></li> <li><p>Amd</p><p>Define (['./mymodule.js '], function (mymodule) {<br>});</p></li> </ul> </ul><p><p>The Package JS module has been shown above and is not repeated here. ES6 modules need to be configured Babel-loader to handle the JS file First.<br>The following shows the configuration file for the packaged es module:</p></p><pre> <code>var webpack = require (' webpack '); var path = require (' path '); var buildpath = path.resolve (__dirname, ' Build '); var nodemodu Lespath = Path.resolve (__dirname, ' Node_modules '); var transferwebpackplugin = require (' transfer-webpack-plugin '); var Config = {entry: [path.join (__dirname, ' src/main.js ')], resolve: {extensions: ["", ". js", ". jsx"]//node_modules : ["web_modules", "node_modules"] (Default Settings)}, output: {path:buildpath, filename: ' app.js '}, Plugins: [new webpack.optimize.UglifyJsPlugin ({compress: {warnings:false}}), New WEBPACK.N Oerrorsplugin (), new Transferwebpackplugin ([{from: ' www '}], path.resolve (__dirname, "src")], module: { Preloaders: [{test:/\. ( Js|jsx) $/, loader: ' eslint-loader ', include: [path.resolve (__dirname, "src/app")], exclude: [nodemodu lespath]},], loaders: [{test:/\.js$/,//note is regular expression, do not add quotation marks Loader: ' Babel-loader?opTional=runtime&stage=0 ',//babel Module related functions Please self-examination, here do not introduce Exclude: [nodemodulespath]}]},//eslint config E Slint: {configfile: '. eslintrc '//rules for eslint},};module.exports = config;</code></pre>Packaging Static Resources <ul> <ul> <li><p>Css/sass/less</p></li> </ul> </ul><p><p>Installing Css-loader and Style-loader</p></p><pre><pre> <code>npm install css-loader --save -devnpm install style-loader --save -dev</code></pre></pre><p><p>Config configuration:</p></p><pre><pre> <code>var config = { entry:path.resolve(__dirname,‘src/main.js‘), resolve:{ extentions:["","js"] }, output:{ path:buildPath, filename:"app.js" }, module:{ loaders:[{ test:/\.css$/, loader:‘style!css‘, exclude:nodemodulesPath }] }}</code></pre></pre><p><p>Style-loader will embed the CSS file into the HTML style tag, and Css-loader will export the CSS as a string, the two basic combinations are used. After the file is packaged, the reference is executed, and the contents of the CSS are inserted into a style tag in the Head.<br>If sass or less is configured in the same way as Above.</p></p> <ul> <ul> <li><p>Images</p></li> </ul> </ul><p><p>You can use Url-loader to convert smaller images into base64 strings embedded in the generated File.<br>Installation:</p></p><pre><pre> <code>npm install url-loader --save -dev</code></pre></pre><p><p>Config configuration:</p></p><pre><pre> <code>var config = { entry:path.resolve(__dirname,‘src/main.js‘), resolve:{ extentions:["","js"] }, output:{ path:buildPath, filename:"app.js" }, module:{ loaders:[{ test:/\.css$/, loader:‘style!css‘,// exclude:nodemodulesPath }, { test:/\.png$/,loader:‘url-loader?limit=10000‘}//限制大小小于10k的 ] }}</code></pre></pre><p><p>CSS file content:</p></p><pre><pre> <code>#container{ color: #f00; background:url(images/logo-201305.png); /*生成完图片会被处理成base64的字符串 注意:不要写‘/images/logo-201305.png‘,否则图片不被处理*/}</code></pre></pre> <ul> <ul> <li><p>Iconfont</p></li> </ul> </ul><p><p>The method of using embedded Iconfont is consistent with the above methods of processing PNG Images. Handled by Url-loader.</p></p><p><p>Config configuration:</p></p><pre><pre> <code>var config = { entry:path.resolve(__dirname,‘src/main.js‘), resolve:{ extentions:["","js"] }, output:{ path:buildPath, filename:"app.js" }, module:{ loaders:[{ test:/\.css$/, loader:‘style!css‘,// exclude:nodemodulesPath }, { test:/\.(png|woff|svg|ttf|eot)$/,loader:‘url-loader?limit=10000‘}//限制大小小于10k的 ] }}</code></pre></pre><p><p>CSS file content:</p></p><pre><pre> <code>@font-face {font-family: ‘iconfont‘;src: url(‘fonts/iconfont.eot‘); /* IE9*/src: url(‘fonts/iconfont.eot?#iefix‘) format(‘embedded-opentype‘), /* IE6-IE8 */url(‘fonts/iconfont.woff‘) format(‘woff‘), /* chrome、firefox */url(‘fonts/iconfont.ttf‘) format(‘truetype‘), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/url(‘fonts/iconfont.svg#iconfont‘) format(‘svg‘); /* iOS 4.1- */}</code></pre></pre><p><p>After the package is executed, the font files are converted into Base64 string contents into the File.<br>Here is a headache problem, that is, each browser supports different font formats, due to the full format of the font packaging, resulting in unnecessary waste of resources.</p></p>Packaging template<p><p>I have a large package of handlebars modules for example, to demonstrate the process of packaging modules. Some templates corresponding to the loader, there may not be the car, I am afraid to achieve loader.</p></p><p><p>Install the required node module first</p></p><pre><pre> <code>npm install handlebars-loader --save -devnpm install handlebars -save//是必须的</code></pre></pre><p><p>Config configuration:</p></p><pre><pre> <code>var config = { entry:path.resolve(__dirname,‘src/main.js‘), resolve:{ extentions:["","js"] }, output:{ path:buildPath, filename:"app.js" }, module:{ loaders:[ { test: /\.html$/, loader: "handlebars-loader" } ] }}</code></pre></pre><p><p>Create a new template file tb.html, directory structure:</p></p><pre><pre> <code>webpack |---index.html |---webpack-config.js |---src |---template | |---tb.html |---main.js</code></pre></pre><p><p>The code for calling the module in Main.js is as Follows:</p></p><pre><pre> <code>var template = require("./template/tp.html");var data={say_hello:"it is handlebars"};var html = template(data);document.getElementById(‘tmpl_container‘).innerHTML = html; </code></pre></pre>Common modules are packaged separately<p><p>This needs to be done through the plugin "commonschunkplugin". This plugin does not need to be installed, because Webpack has included him in it.<br>Next we look at the configuration file:</p></p><pre><pre> <code>var config = { entry:{app:path.resolve(__dirname,‘src/main.js‘), vendor: ["./src/js/common"]},//【1】注意这里 resolve:{ extentions:["","js"] }, output:{ path:buildPath, filename:"app.js" }, module:{ loaders:[{ test:/\.css$/, loader:‘style!css‘, exclude:nodemodulesPath } ] }, plugins:[ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), //【2】注意这里 这两个地方市用来配置common.js模块单独打包的 new webpack.optimize.CommonsChunkPlugin({ name: "vendor",//和上面配置的入口对应 filename: "vendor.js"//导出的文件的名称 }) ]}</code></pre></pre><p><p>The directory structure is now like this:</p></p><pre><pre> <code>webpack |---index.html |---webpack-config.js |---src |---main.js |---js |---a.js //a里面require了common |---common.js</code></pre></pre><p><p>Execution of Webpack generates App.js and Common.js two Files.</p></p>Multiple entrances<p><p>Config configuration:</p></p><pre><pre> <code>var config = { entry:{ m1:path.resolve(__dirname,‘src/main.js‘), m2:path.resolve(__dirname,‘src/main1.js‘) },//注意在这里添加文件的入口 resolve:{ extentions:["","js"] }, output:{ path:buildPath, filename:"[name].js"//注意这里使用了name变量 } }</code></pre></pre>Webpack-dev-server<p><p>During the development process, we certainly do not want to manually execute the webpack command to debug the program after each Modification. So we can use the Webpack-dev-server module instead of annoying execution commands. It listens to the file, automatically compiles and refreshes the Browser's page after the file has been Modified. In addition, the result of the compilation is stored in memory, not the Entity's files, so it is not visible, because this will compile Faster. It comes to mind with a light weight express server.<br>Installation:</p></p><pre><pre> <code>npm install webpack-dev-server --save -dev</code></pre></pre><p><p>Config configuration:</p></p><pre><pre> <code>var config = { entry:path.resolve(__dirname,‘src/main.js‘), resolve:{ extentions:["","js"] }, //Server Configuration options devServer:{ contentBase: ‘‘, //静态资源的目录 相对路径,相对于当前路径 默认为当前config所在的目录 devtool: ‘eval‘, hot: true, //自动刷新 inline: true, port: 3005 }, devtool: ‘eval‘, output:{ path:buildPath, filename:"app.js" }, plugins: [ new webpack.HotModuleReplacementPlugin(),//这个好像也是必须的,虽然我还没搞懂它的作用 new webpack.NoErrorsPlugin() ]}</code></pre></pre><p><p>My directory Structure:</p></p><pre><pre> <code>webpack |---index.html |---webpack-config.js//我把静态资源目录配置在了这里 |---src |---main.js |---js |---a.js |---common.js</code></pre></pre><p><p>Execute command:</p></p><pre><pre> <code>webpack-dev-server --config webpack-dev-config.js --inline --colors</code></pre></pre><p><p>Default Access Address: http://localhost:3000/index.html (varies by Configuration)</p></p><p><p>One thing to declare is to refer directly to "app.js" in index.html (the HTML file that references the exported results), not to the parent directory, because at this point the app.js is not related to the directory of the output configuration in memory:</p></p><pre><pre> <code><script type="text/javascript" src="app.js"></script></code></pre></pre><p><p>Detailed documentation is here:<br>Http://webpack.github.io/docs/webpack-dev-server.html</p></p><p><p>Webpack Common Function Introduction</p></p></span>

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.