Antecedents feed

On an article introduces the front of the more popular various editor, as well as a variety of popular packaging, finally gives an example of a Gulp, this example was 14 years, there are still some space can be optimized, is not discussed, this article is mainly about the way of the hot pack to build – Webpack way of use.

Main course — no appetizer soup

In fact, Webpack entry guide articles are very many, configuration methods are also various, here I recommend the title leaf dagod’s entry level guide -Webpack entry refers to fans, if you do not know what Webpack is or is not very clear about the meaning of the configuration of the developer, you can read this article to sweep the illiteracy. After all, my article is not particularly basic.

A, base. Js

var path = require('path') var baseConfig = { resolve: { extensions: ['', '.js'], fallback: [path.join(__dirname, '../node_modules')], alias: { 'src': path.resolve(__dirname, '.. /src'), 'assets': path.resolve(__dirname, '.. /src/assets'), 'components': path.resolve(__dirname, '.. /src/components') } }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url?limit=8192&context=client&name=[path][name].[hash:7].[ext]' }, { test: /\.css$/, loader: 'style!css!autoprefixer', }, { test: /\.scss$/, loader: 'style!css!autoprefixer!sass' }] } }; module.exports = baseConfig;Copy the code

Read the basic configuration:

1. Resolve affected configuration items when resolve module dependencies.

  • Extensions determine which file suffixes can be omitted when referenced, and Webpack helps you complete the name.
  • Fallback If webpack directories cannot find the relevant modules at root and modulesDirectories, which folder should you go to find modules
  • Alias that everyone should be familiar, have requirejs, is an alias, help you quickly point to the file path, write less code, and need not care about hierarchy, it is important to note: the SCSS like CSS reference to add in the precompiled ~, so as to make loader recognition is an alias reference path.

2, The module parse different files using which loader, this is a simple, many articles, not to say, note that here, SCSS can be replaced by your own precompiler, such as: Sass, less, stylus, etc., or just postCSS, or you can use a generic method and fill it in later.

2. Development environment configuration — Config

var webpack = require('webpack'); var path = require('path') var merge = require('webpack-merge') var baseConfig = require('./webpack.base') var getEntries = require('./getEntries') var hotMiddlewareScript = 'webpack-hot-middleware/client? reload=true'; var assetsInsert = require('./assetsInsert') module.exports = merge(baseConfig, { entry: getEntries(hotMiddlewareScript), devtool: '#eval-source-map', output: { filename: './[name].[hash].js', path: path.resolve('./dist'), publicPath:'./dist' }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"development"' } }), new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new assetsInsert() ] })Copy the code

Some of the difficulties with this configuration:

1, however, is used to configure the entry documents, generally a lot of man is his own handwriting, or SPA page, there is only one entrance, it is easy to write, but the company, in many cases, is the need for multiple entry, which is more routing Url, this time the entrance to the configuration is more troublesome, I’m here is to put a single configuration file, Our company is implemented by rules, that is, all main.js files in a folder are considered as entry files, and the rest are ignored.

function getEntry(hotMiddlewareScript) { var pattern = paths.dev.js + 'project/**/main.js'; var array = glob.sync(pattern); var newObj = {}; array.map(function(el){ var reg = new RegExp('project/(.*)/main.js','g'); reg.test(el); if (hotMiddlewareScript) { newObj[RegExp.$1] = [el, hotMiddlewareScript]; } else { newObj[RegExp.$1] = el; }}); return newObj; }Copy the code

2. AssetsInsert is used for template substitution, a small plugin that replaces the value of the template with the packaged CSS or JS.

Package environment configuration — Production

var webpack = require('webpack');
var path = require('path')
var merge = require('webpack-merge')
var baseConfig = require('./webpack.base')
var getEntries = require('./getEntries')
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var assetsInsert = require('./assetsInsert')

var productionConf = merge(baseConfig, {
    entry: getEntries(),
    output: {
        filename: './[name].[hash].js',
        path: path.resolve('./public/dist'),
        publicPath: './'
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new ExtractTextPlugin('./[name].[hash].css', {
            allChunks: true
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new webpack.optimize.OccurenceOrderPlugin(),
        new assetsInsert()
    ]
})

productionConf.module.loaders = [
             {
                test: /\.js$/,
                loader: 'babel',
                exclude: /node_modules/
            }, {
                test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)(\?.*)?$/,
                loader: 'url?limit=8192&context=client&name=[path][name].[hash:7].[ext]'
            },
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract('style', 'css'),
            },
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract('style', 'css!sass')
            }]

module.exports = productionConfCopy the code

1, Use the ExtractTextPlugin to package CSS, so to eliminate the original base loaders, rewrite a new one, at the bottom.

2, UglifyJsPlugin to JS compression code. There’s nothing else to explain. Same thing.

Build commands

require('shelljs/global') env.NODE_ENV = 'production' var ora = require('ora') var webpack = require('webpack') var webpackConfig = require('./webpack.production.config') var spinner = ora('building for production... ') spinner.start() var staticPath = __dirname + '/.. /public/dist/' rm('-rf', staticPath) mkdir('-p', staticPath) webpack(webpackConfig, function (err, stats) { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n') })Copy the code

Write a build.js file and add script arguments to package.json

"Build ": "node build.js"// Remember to write your own build.js path hereCopy the code

Dessert (macarons) – a little greasy

The above configuration can be changed, for example if you add it to loaders

{
  test: /\.vue$/,
  loader: 'vue'
}Copy the code

You can build a vuejs package that supports.vue files. Similarly, you can modify it to support JSX and add some ReactJS modules to run reactJS stuff.

And you can change the type of the Css precompiler as much as you like, or you can configure all the types as we mentioned earlier,

var path = require('path') var config = require('.. /config') var ExtractTextPlugin = require('extract-text-webpack-plugin') exports.assetsPath = function (_path) { return path.posix.join(config.build.assetsSubDirectory, _path) } exports.cssLoaders = function (options) { options = options || {} // generate loader string to be used with extract text plugin function generateLoaders (loaders) { var sourceLoader = loaders.map(function (loader) { var extraParamChar if (/\? /.test(loader)) { loader = loader.replace(/\? /, '-loader? ') extraParamChar = '&' } else { loader = loader + '-loader' extraParamChar = '? ' } return loader + (options.sourceMap ? extraParamChar + 'sourceMap' : '') }).join('! ') if (options.extract) { return ExtractTextPlugin.extract('vue-style-loader', sourceLoader) } else { return ['vue-style-loader', sourceLoader].join('! ') } } // http://vuejs.github.io/vue-loader/configurations/extract-css.html return { css: generateLoaders(['css']), postcss: generateLoaders(['css']), less: generateLoaders(['css', 'less']), sass: generateLoaders(['css', 'sass?indentedSyntax']), scss: generateLoaders(['css', 'sass']), stylus: generateLoaders(['css', 'stylus']), styl: generateLoaders(['css', 'stylus']) } } // Generate loaders for standalone style files (outside of .vue) exports.styleLoaders = function (options) { var output = [] var loaders = exports.cssLoaders(options) for (var extension in loaders) { var loader = loaders[extension] output.push({ test: new RegExp('\\.' + extension + 'Copy the code

This is to add all the pre-compiled CSS to the configuration.

To sum up — check

Webpack varied, even if a loaders have several different configurations, let a person is very headache, the key is a lot of plug-in own documents nor qing chu, not everyone is confused, my experience is more, try more test itself to write a written, look at the command line printing mistakes, to find the reason, don’t panic at the sight of the error, Many novices are most prone to make mistakes when they see mistakes, they doubt their life. They must read the wrong records in the newspaper. There are generally tips, and they should solve the corresponding problems according to the tips.

In the next chapter we cover Nodejs.