directory

At the beginning of the contact with Webpack, it was almost unbearable, now look back, make a note, of course reference a lot of articles. This is a summary of webpack resources for vue development. The webpack framework will be listed in the Webpack series tutorial Webpack – Confusing places Express with webpack full stack auto-refresh Webpack dump-ass guide

Start the instruction

"Scripts ": {"dev": "node build/dev-server.js", // "build": "node build/build.js",// package "lint": "eslint --ext .js,.vue src" },Copy the code

webpack.base.conf.js

Webpack basic configuration

var path = require('path') var config = require('.. /config') var utils = require('./utils') var projectRoot = path.resolve(__dirname, '.. /') var env = process.env.NODE_ENV // check env & config/index.js to decide whether to enable CSS source maps for the //  various preprocessor loaders added to vue-loader at the end of this file var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap) var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap) var UseCssSourceMap = cssSourceMapDev | | cssSourceMapProd / / configuration file need to pass the module. The content of the exposed the module exports. Exports = {/ / configuration need to pack the entrance to the file, Values can be strings, arrays, objects. // 1. String: entry: './entry' // 2. String: entry: ['./entry1','entry2'] (multiple entries) // 3. Object: entry: {alert/index': Path.resolve (pagesDir, './alert/index/page ')} './ SRC /main.js'}, output: {// output has its own set of rules. Indicates that the root of the build file requires a ** absolute path ** path just tells Webpack where the results are stored path: Config.build. assetsRoot, // publicPath represents a URL path (pointing to the following directory of the build file), // The "publicPath" item is used by many Webpack plug-ins to update the URL values embedded in CSS, HTML files in production mode. // For example, In a localhost CSS file you might use a url like "./test.png "to load images, but in production mode the" test.png "file might be located to the CDN and your Node.js server might run on top of HeroKu.  // This means that in production you have to manually update all files with CDN urls. // background-image: url('./test.png'); // background-image: url('./test.png'); Image {// background-image: url('https://someCDN/test.png'); / /}! [](http://images2015.cnblogs.com/blog/1108527/201703/1108527-20170304195944626-432609161.png) publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : Config. Dev. AssetsPublicPath, / / filename attribute represents how to name the entry documents, rules are three: // [name] specifies the name of the entry file, which is the key of the entry parameter. // [hash] specifies a hash version of this compilation. Note that the [hash].js // value is the same as the file generated during the same compilation. At the cache level, this is equivalent to a full replacement. filename: '[name].js'}, // is used to configure the matching of dependent files, such as the alias configuration of dependent files, the module lookup directory, the default lookup // file suffix // resolve.root. Resolve: {extensions: ['', '.js', '.vue', '.json'], fallback: [path.join(__dirname, '../node_modules')], // Used to configure the alias of the dependent file, the value is a pair, the key of the object is the alias, the value is the actual path alias: {'vue$': 'vue/dist/vue.common.js', 'src': path.resolve(__dirname, '.. /src'), 'assets': path.resolve(__dirname, '.. /src/assets'), 'components': path.resolve(__dirname, '.. / SRC /components')}}, resolveLoader: {fallback: [path.join(__dirname, '../node_modules')]}, resolveLoader: {fallback: [path.join(__dirname, '../node_modules')]}, { preLoaders: [ { test: /\.vue$/, loader: 'eslint', include: projectRoot, exclude: /node_modules/ }, { test: /\.js$/, loader: 'eslint', include: projectRoot, exclude: /node_modules/ } ], loaders: [// Webpack has a plugin-like mechanism called Loader, through which Webpack can handle each specific resource accordingly // the 1.test parameter is used to indicate which resource the current configuration item applies to. The value should be a condition. The include parameter specifies the directories/files that the Loader configuration applies only to. The include parameter specifies the directories/files that the Loader configuration applies only to. The include parameter specifies the condition. // The include argument is used to indicate the directory; note that when both are used together, the relationship is actually and. // 4. Loader /loaders parameter, used to indicate which or which loaders to use to process the target resource, is actually the same meaning, but the writing method is not the same, I recommend using loader to write a line, multiple loaders between use! This form is similar to the concept of pipeline, or functional programming. 'CSS?! Postcss! Less', it is clear that the target resource is first processed by less-loader and then sent to postCSs-loader for further processing, and finally to CSS-loader. /\.vue$/, loader: 'vue' }, { test: /\.js$/, loader: 'babel', include: projectRoot, exclude: /node_modules/ }, { test: /\.json$/, loader: 'json' }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url', query: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url', query: { limit: 10000, name: Utils. AssetsPath ('fonts/[name].[hash:7].[ext]')}}, // expose-loader Resolve.resolve ('jquery'), // This loader configuration item targets the jquery loader in NPM: 'expose?$! Expose? JQuery ', // Declare the jQuery object as a global variable 'jQuery', and then declare it as a global variable' $'},]}, eslint: {expose: $! require('eslint-friendly-formatter') }, vue: { loaders: utils.cssLoaders({ sourceMap: UseCssSourceMap}), // resolve. Vue parses some features of the style part of the file, such as scoped postcss: [require('autoprefixer')({browsers: ['last 2 versions'] }) ] } }Copy the code

webpack.dev.conf.js

var config = require('.. /config') var webpack = require('webpack') var merge = require('webpack-merge') var utils = require('./utils') var baseWebpackConfig = require('./webpack.base.conf') var HtmlWebpackPlugin = require('html-webpack-plugin') // add hot-reload related code to entry chunks Object.keys(baseWebpackConfig.entry).forEach(function (name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) }) module.exports = merge(baseWebpackConfig, { module: { loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) }, // eval-source-map is faster for development devtool: '#eval-source-map', plugins: // new webpack.defineplugin ({'process.env': config.dev.env }), // https://github.com/glenjamin/webpack-hot-middleware#installation--usage new webpack.optimize.OccurrenceOrderPlugin(),  new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: }), // it can automatically load other modules that the current module depends on and has made aliases to inject into the current module. ProvidePlugin + expose-loader jq // // If you consider jQuery to be a normal JS module to load, then, $($($)); $($($)); $($($)); $($($($)); Extend (object) and jquery.extend (object) are two methods provided by jQuery to mount the plugin's own methods to the jQuery ($) object. The traditional way to reference jQuery and // its plug-ins is to load jQuery itself with <script> and then load its plug-ins in the same way; // jQuery sets jQuery objects as global variables (including $), so plugins can easily find jQuery objects and mount their own methods. // // And Webpack, as a building tool that follows the principle of modularization, is naturally to separate the context of each module to // to reduce the influence between each other; In other words, when we require jQuery, we don't actually set the jQuery object as a global variable. At this point, the problem is obvious. JQuery plugins can't find jQuery objects because there are no local jQuery variables in their respective // text environments (no requi // re statements because there are no AMD/CMD adaptors). No global variable jquery. // // A: The mechanism of the ProvidePlugin is: When webpack is loaded into a JS module, it automatically requires the js module // expose-loader specified in the value configuration when there is an undefined variable whose name matches the key specified in the // (string matching exactly) configuration. // // B:externals calls jq // Externals is an item in the webpack configuration used to "disguise" a global variable as the exports of a JS module, as in the following configuration:  // externals: {'jquery': Var $= require(' jQuery');} The window, // jQuery is returned to it, as opposed to the ProvidePlugin + expose-loader scheme above, which first loads jQuery with // <script> to satisfy the needs of older jQuery plug-ins. New webpack.ProvidePlugin({$: "jquery", jquery: "jquery", "window.jquery ": "jquery", 'window.$': 'jquery', }) ] })Copy the code

webpack.prod.conf.js

var path = require('path') var config = require('.. /config') var utils = require('./utils') var webpack = require('webpack') var merge = require('webpack-merge') var baseWebpackConfig = require('./webpack.base.conf') var ExtractTextPlugin = require('extract-text-webpack-plugin') var HtmlWebpackPlugin = require('html-webpack-plugin') var env = config.build.env var webpackConfig = merge(baseWebpackConfig, { module: { loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, devtool: config.build.productionSourceMap ? '#source-map' : false, output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') }, vue: { loaders: utils.cssLoaders({ sourceMap: config.build.productionSourceMap, extract: True})}, // webpack plugin location, has fixed usage // 1. Use the Plugin's initialization method and pass in the Plugin's default parameters to initialize and generate an instance. // 2. Insert this instance into the plugins parameter (array type) in the WebPack configuration file. // // 1. plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ 'process.env': env }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.OccurrenceOrderPlugin(), // extract css into its own file new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // See https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin ({/ / filename generated web page's HTML name, Filename: config.build.index, template: 'index.html', inject: // inject where to insert the <script> used to load js files, the default is to insert the <body> // end, if set to 'head' then insert <script> into <head>. true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency'}), // CommonsChunkPlugin () {// CommonsChunkPlugin () {// CommonsChunkPlugin () {// CommonsChunkPlugin ();  // name: [name], [hash], [chunkhash], // minChunks A js module is how much load a chunk is a public code new webpack.optimize.Com monsChunkPlugin ({name: 'vendor', minChunks: function (module, count) { // any required modules inside node_modules are extracted to vendor return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }) ] }) if (config.build.productionGzip) { var CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '\\.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8}))} module.exports = webpackConfigCopy the code