webpack learning 10 days to get webpack4

 

 

12-day course - Multi-page: multiple entry, match multiple packaged js


const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: {
        home: './src/home.js',
        other: './src/other.js'
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/home.html',
            filename: 'home.html',
            chunks:['home']
        }),
        new HtmlWebpackPlugin({
            template: './src/other.html',
            filename: 'other.html',
            chunks:['other']
        })
    ]
}

 

Supplementary chapters: webpack-mode


 mode is divided into development / production, the default is Production's . The default configuration of each option are as follows (common configuration item refers to two attributes are present):

 common:

// parent chunk in the chunk resolved will be deleted 
optimization.removeAvailableModules: to true 
// delete empty of chunks are 
optimization.removeEmptyChunks: to true 
// merge duplicate chunk 
optimization.mergeDuplicateChunks: to true

 

production 

// Properties Related 
Performance: {hints: " error " ....}
 // sub-chunk chunk some way have been determined and marked, the sub-chunks when loading a larger block having to load 
optimization.flagIncludedChunks : to true 
// to frequently used ids shorter value 
optimization.occurrenceOrder: to true 
// to determine the export of each module to be used 
optimization.usedExports: to true 
// identification flag package.json or rules sideEffects 
optimization.sideEffects: to true 
/ / try to find a block diagram of a secure connection to the segment may be a single module. - - 
optimization.concatenateModules: to true 
// use uglify-js compressed code 
optimization.minimize: to true

development

// debug 
DevTools: eval
 // cache module, to avoid rebuilding them when not changed. 
Cache: to true 
// dependency cache resolved, avoid re-parsing them. 
module.unsafeCache: to true 
// introduced in the bundle related comments, "The information contained module" 
output.pathinfo: to true 
// determine export each module in where possible, be used for other optimization or code generation. 
optimization.providedExports: to true 
// find a chunk shared module, taken out to generate a separate chunk 
optimization.splitChunks: to true 
// code to create a separate chunk to run webpack when 
optimization.runtimeChunk: to true 
// not written to compile error output 
optimization.noEmitOnErrors: to true 
// to the module a meaningful name instead of IDS 
optimization.namedModules:to true 
// to die chunk instead of meaningful names IDS 
optimization.namedChunks: to true

 

Will webpack run time based mode setting a global variable process.env.NODE_ENV,

Here process.env.NODE_ENV not a node in the environment variable, but webpack.DefinePlugin global variables defined, allowing you to execute different code depending on the environment.

Production environment, will be automatically deleted when the code is not up to uglify package code that is compressed after the final production environment of code:

 

 

13-day course - Configure source-map


 

Installation depends

npm install -D babel-loader @babel/core @babel/preset-env 

npm install webpack-dev-server --save-dev

devtool set of understandings, eval can be understood as the emission is not produced compilation stage
  // DevTools: 'Source-Map', // generate a file, it can be displayed in rows and columns
   // DevTools: 'the eval-Source-Map', // do not actually generate a file, may be displayed in rows and columns
   // DevTools: ' Source---Module1 Cheap Map ', // do not display column, generate a file 
  DevTools: ' Cheap-Module1 the eval-Source-Map- ' , // do not display column, no file

 

Test Code src / home.js:

class Demo{
    constructor(){
        console.loga();
    }
}
let d=new Demo();

 

const path = the require ( ' path ' );
 const HtmlWebpackPlugin the require = ( ' HTML-WebPACK-plugin ' ); 

module.exports = { 
  MODE: ' Production ' , 
  entry: { 
    Home: ' ./src/home.js ' , 
  }, 
  Output: { 
    filename: ' The index.js ' , 
    path: path.resolve (__ dirname, ' dist ' ) 
  }, 
  // DevTools: 'Source-Map', // generate a file, it can be displayed in rows and columns
  // devtool: 'the eval-Source-Map', // do not actually generate a file, may be displayed in rows and columns
   // devtool: 'Cheap-Module1-Source-Map', // do not display column, generate a file 
  DevTools: ' Module1 the eval---Cheap-Source Map ' , // do not display column, no file 
  Module1: { 
    the rules: [ 
      { 
        Test: /\.m?js$/ , 
        the exclude: / (the node_modules | bower_components) / , 
        use: { 
          Loader: ' Babel-Loader ' , 
          Options: { 
            Presets: [ ' @ Babel / PRESET-the env '  ]
          }
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/home.html',
      filename: 'index.html',
      chunks: ['home']
    })
  ]
}

 

 

14 chapters: watch usage, execute build the beginning npm run


 

After completion of code changes, build immediately, a compile-file,

 

"Start": "webpack-dev-server", does not produce a file, so use watch

 

 

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'production',
  entry: {
    home: './src/home.js',
  },
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist')
  }, 
  watch:true,
  watchOptions:{
    poll:1000 , // check every second change 
    aggregateTimeout: 500 , // stabilization delay, after the input 500 seconds, 
    ignored: / the node_modules / // ignored:. "Files / ** / * JS" 
  }, 
  Module1: { 
    the rules : [ 
      { 
        Test: /\.m?js$/ , 
        the exclude: / (the node_modules | bower_components) / , 
        use: { 
          Loader: ' Babel-Loader ' , 
          Options: { 
            Presets: [ ' @ Babel / PRESET-the env ' ] 
          } 
        } 
      } 
    ] 
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/home.html',
      filename: 'index.html',
      chunks: ['home']
    })
  ]
}

 

 

 

15: webpack small plug presentations

 


 

cleanWebpackPlugin:npm install clean-webpack-plugin -D

Key Code:

const {} = CleanWebpackPlugin the require ( ' Clean-WebPACK-plugin ' ); // introducing purge plug file 
new new CleanWebpackPlugin ()

Official Description: Detailed Description

        /**
         * All files inside webpack's output.path directory will be removed once, but the
         * directory itself will not be. If using webpack 4+'s default configuration,
         * everything under <PROJECT_DIR>/dist/ will be removed.
         * Use cleanOnceBeforeBuildPatterns to override this behavior.
         *
         * During rebuilds, all webpack assets that are not used anymore
         * will be removed automatically.
         *
         * See `Options and Defaults` for information
         */
所有output.path目录都会被一次删除,目录本身不会删除

 

 

 

copyWebPackPlugin:

 

const CopyWebpackPlugin = require('copy-webpack-plugin'); // 文件拷贝
new CopyWebpackPlugin([{from:'./doc',to:'./'}])

 

bannerPlugin:

= WebPACK the require the let ( ' WebPACK ' );
 new new webpack.BannerPlugin ( ' copyright violation reserved Copyright 2019 ' )

 

 This section webpack profile

 

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin'); // 引入清除文件插件
const CopyWebpackPlugin  = require('copy-webpack-plugin'); // 引入清除文件插件
let webpack=require('webpack');

module.exports = {
  mode: 'development',
  entry: {
    home: './src/home.js',
  },
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist')
  }, 
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/home.html',
      filename: 'index.html',
      chunks: ['home']
    }),
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin([{from:'./doc',to:'./'}]),
    new webpack.BannerPlugin('版权所有,违反必究 2019 copyright')
  ]
}

 

 16章节:webpack跨域问题


webpack端口默认是8080 如果请求这么写,会跨域,跨域是浏览器本身的限制,如果使用浏览器跨域设置,可以请求到数据

1:devServer-proxy设置

本地express服务器:localhost:3000/api/user

代理设置:proxy:{'/api':'http://localhost:3000'}

但是不是服务端每个接口都是api开头的,所以需要用下面的方式 本地express服务器:localhost:
3000/user 代理devServer设置
  proxy:{
    '/api':{
     target:'http://localhost:3000',
     pathRewrite:{'/api':''}
    }
  }
 

2:单纯模拟数据mock 启动钩子函数

 

 

3:有服务端,但是不想用代理处理,用express 启动webpack 端口用express端口

npm install webpack-dev-middleware --save-dev   //安装依赖
server.js

let express = require('express');
let config=require('./webpack.config');
const webpack = require('webpack');
const middleware = require('webpack-dev-middleware');
const compiler = webpack(config);
let app = express();
app.use(
  middleware(compiler, {
  })
);
app.get('/api/user', (req, res) => {
    res.json({ "name": "珠峰设计-express" });
})
app.listen(3000);

 

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin'); // 引入清除文件插件
const CopyWebpackPlugin = require('copy-webpack-plugin'); // 引入清除文件插件
let webpack = require('webpack');

module.exports = {
  mode: 'development',
  entry: {
    home: './src/home.js',
  },
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    before(app) {
      console.log(app);
      app.get('/before', (req, res) => {
        res.json({ "name": "我试mock数据-before" });
      })
    },
    port: 9000,
    /*proxy:{
      '/api':'http://localhost:3000'
    } */
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        pathRewrite: { '/api': '' }//需要先启动3000端口的服务
      }
    }
  },

  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/home.html',
      filename: 'index.html',
      chunks: ['home']
    }),
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin([{ from: './doc', to: './' }]),
    new webpack.BannerPlugin('版权所有,违反必究 2019 copyright')
  ]
}

 

Guess you like

Origin www.cnblogs.com/liuguiqian/p/11287631.html
Recommended