webpack

webpack

Entry

entry ,webpack ,

entry , webpack

context

webpack , , Webpack

webpack --context
context
,
context
entry

entry

string'./app/entry'
array['./app/entry1', './app/entry2']
object{ a: './app/entry-a', b: ['./app/entry-b1', './app/entry-b2']} Chunk

array
output.library

Chunk

Webpack Chunk Chunk Entry

  • entry
    string
    array
    Chunk Chunk
    main
  • entry
    object
    Chunk Chunk
    object

Entry

// entry: () => { return { a:'./pages/a', b:'./pages/b', } }; // entry: () => { return new Promise((resolve)=>{ resolve({ a:'./pages/a', b:'./pages/b', }); }); };

Output

output
output
object

filename

output.filename
string

filename: 'bundle.js'

Chunk Webpack Chunk Chunk

filename: '[name].js' /** * id Chunk 0 name Chunk hash Chunk Hash chunkhash Chunk Hash // hash chunkhash [hash:8] 8 Hash 20 /

[name]
name
[name]
Chunk

chunkFilename

entry
chunk
chunk

path

output.path
string Node.js
path

path: path.resolve(__dirname, 'dist_[hash]')

publicPath

output.publicPath
URL string
''

filename:'[name]_[chunkhash:8].js' publicPath: 'https://cdn.example.com/assets/'

output.path
output.publicPath
hash
Hash

crossOriginLoading

output.crossOriginLoading
crossorigin

script crossorigin

  • anonymous
    ( ) Cookies
  • use-credentials
    Cookies

crossorigin

libraryTarget library

webpack , .

  • output.library
  • output.libraryTarget
    ,
    • var ( ) ( webpack )
      var
      , , output.library
    • commonjs CommonJS , export library node
    • commonjs2, module.export export library node
    • amd, define library script RequireJS
    • umd, commonjs commonjs2 amd node umdNamedDefine: true globalObject: this

Module

module
,Webpack CSS
main.css
JavaScript Webpack CSS JavaScript Webpack Loader

rules

rules
Loader
rules

  1. test
    include
    exclude
    Loader
  2. use
    Loader Loader Loader Loader
  3. Loader
    enforce
    Loader
module: { rules: [ { // JavaScript test: /\.js$/, // babel-loader JavaScript //?cacheDirectory babel-loader babel use: ['babel-loader?cacheDirectory'], // src js Webpack include: path.resolve(__dirname, 'src') }, { // SCSS test: /\.scss$/, // Loader SCSS // sass-loader css-loader style-loader use: ['style-loader', 'css-loader', 'sass-loader'], // node_modules exclude: path.resolve(__dirname, 'node_modules'), }, { // file-loader test: /\.(gif|png|jpe?g|eot|woff|ttf|svg|pdf)$/, use: ['file-loader'], }, ] }

Loader Object babel-loader

use: [ { loader:'babel-loader', options:{ cacheDirectory:true, }, //enforce:'post' Loader //enforce pre Loader enforce:'post' }, // Loader ]

test include exclude

{ test:[ /\.jsx?$/, /\.tsx?$/ ], include:[ path.resolve(__dirname, 'src'), path.resolve(__dirname, 'tests'), ], exclude:[ path.resolve(__dirname, 'node_modules'), path.resolve(__dirname, 'bower_modules'), ] }

noParse

noParse
Webpack

noParse
RegExp
[RegExp]
function

// noParse:/jquery|chartjs/// Webpack 3.0.0 noParse: (content)=> { //content // true or false return/jquery|chartjs/.test(content);}

parser

JavaScript ,

parser

module: { rules: [ { test: /\.js$/, use: ['babel-loader'], parser: { amd: false, // AMD commonjs: false,// CommonJS system: false,// SystemJS harmony: false,// ES6 import/export requireInclude: false,// require.include requireEnsure: false,// require.ensure requireContext: false,// require.context browserify: false,// browserify requireJs: false,// requirejs } }, ]}

Resolve

Resolve Webpack ,Webpack JavaScript

alias

resolve.alias

//Webpack alias resolve:{ alias:{ components: './src/components/' }}// alias components ./src/components/

import Button from 'components/button'
alias
import Button from'./src/components/button'

resolve:{ alias:{ 'react$': '/path/to/react.min.js' }}//react$ react import 'react' import '/path/to/react.min.js'

mainFields

npm

import * as D3 from "d3"
package.json
webpack
target

mainFields: ["module", "main"]//D3 package.json { ... main: 'build/d3.Node.js', browser: 'build/d3.js', module: 'index', ...}

import * as D3 from "d3"
browser
browser
mainFields
webpack Node.js
module

Webpack

mainFields
,

//Webpack mainFields mainFields mainFields: ['browser', 'main']

extensions

Webpack

resolve.extensions

extensions: ['.js', '.json']

require('./data')
Webpack
./data.js
./data.json

modules

resolve.modules
Webpack
node_modules
import '../../../components/button'
modules
./src/components
modules

modules:['./src/components','node_modules']// import 'button'

descriptionFiles

resolve.descriptionFiles
package.json

descriptionFiles: ['package.json']

enforceExtension

resolve.enforceExtension
true
import './foo'
import './foo.js'

enforceModuleExtension

enforceModuleExtension
enforceExtension
enforceModuleExtension
node_modules
,
enforceModuleExtension
enforceExtension
enforceExtension:true
enforceModuleExtension:false

Plugin

Plugin Webpack Webpack

Plugin

plugins
Plugin Plugin

const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');module.exports = { plugins: [ // common new CommonsChunkPlugin({ name: 'common', chunks: ['a', 'b'] }), ]};

DevServer

DevServer HTTP Webpack Webpack WebSocket

  1. HTTP
  2. Source Map
npm i -D webpack-dev-server

webpack-dev-server
DevServer

package.json script

"dev": "webpack-dev-server"

: "webpack-dev-server": "^3.11.2"+ "webpack-cli": "^3.3.12",

hot

devServer.hot
DevServer

inline

DevServer DevServer

devServer.inline
Chunk DevServer
inline

  • inline
    DevServer
  • inline
    DevServer iframe iframe
    http://localhost:8080/webpack-dev-server/

DevServer

inline

historyApiFallback

historyApiFallback: { // rewrites: [ ///user user.html { from:/^\/user/, to: '/user.html' }, { from:/^\/game/, to: '/game.html' }, // index.html { from:/./, to: '/index.html' }, ]}

contentBase

devServer.contentBase
DevServer HTTP DevServer
public
DevServer

devServer:{ contentBase: path.join(__dirname, 'public')}

headers

devServer.headers
HTTP HTTP

devServer:{ headers: { 'X-foo':'bar' }}

host

devServer.host
DevServer DevServer
--host 0.0.0.0
host
127.0.0.1
DevServer HTTP

port

devServer.port
DevServer 8080 8080 8081 8081 8082

allowedHosts

devServer.allowedHosts
HTTP HOST

allowedHosts: [ // 'host.com', 'sub.host.com', //host2.com *.host2.com '.host2.com']

https

DevServer HTTP HTTPS HTTPS HTTP2 Service Worker HTTPS HTTPS

devServer:{ https: true}

DevServer HTTPS

devServer:{ https: { key: fs.readFileSync('path/to/server.key'), cert: fs.readFileSync('path/to/server.crt'), ca: fs.readFileSync('path/to/ca.pem') }}

open

devServer.open
DevServer
devServer.openPage
URL

Target

target
Webpack

target
web
( )
node
Node.js
require
Chunk
async-node
Node.js Chunk
webworker
WebWorker
electron-main
Electron
electron-renderer
Electron

target:'node'
Node.js
require('fs')
fs
Chunk

Devtool

devtool
Webpack Source Map
false
Source Map Source Map

module.export = { devtool: 'source-map'}

Watch WatchOptions

Webpack Webpack

module.export = { watch: true}

DevServer

Webpack

watchOptions
:

module.export = { // watchOptions // false watch: true, // // watchOptions: { // // ignored:/node_modules/, // 300ms // 300ms aggregateTimeout: 300, // // 1000 poll: 1000 }}

Externals

Externals Webpack Webpack

JavaScript HTML HEAD

<script src="path/to/jquery.js"></script>

externals
Webpack JavaScript
externals
:

module.export = { externals: { // jquery jQuery jquery: 'jQuery' }}

ResolveLoader

ResolveLoader Webpack Loader Loader Webpack Loader Loader Loader

ResolveLoader

module.exports = { resolveLoader:{ // Loader modules: ['node_modules'], // extensions: ['.js', '.json'], // mainFields: ['loader', 'main'] }}

const path = require('path');module.exports = { //entry Webpack Entry // string | object | array entry: './app/entry',// 1 1 entry: ['./app/entry1', './app/entry2'],// 1 2 entry: {// 2 a: './app/entry-a', b: ['./app/entry-b1', './app/entry-b2'] }, // Webpack output: { // string path: path.resolve(__dirname, 'dist'), // filename: 'bundle.js',// filename: '[name].js',// entry entry filename: '[chunkhash].js',// hash // URL string publicPath: '/assets/',// publicPath: '',// publicPath: 'https://cdn.example.com/',// CDN // string // library: 'MyLibrary', // var // umd | umd2 | commonjs2 | commonjs | amd | this | var | assign | window | global | jsonp libraryTarget: 'umd', // boolean pathinfo: true, // Chunk chunkFilename: '[id].js', chunkFilename: '[chunkhash].js', //JSONP jsonpFunction: 'myWebpackJsonp', // Source Map sourceMapFilename: '[file].map', // devtoolModuleFilenameTemplate: 'webpack:///[resource-path]', // crossOriginLoading: 'use-credentials', crossOriginLoading: 'anonymous', crossOriginLoading: false, }, // module: { rules: [// Loader { test:/\.jsx?$/,// Loader include: [// path.resolve(__dirname, 'app') ], exclude: [// path.resolve(__dirname, 'app/demo-files') ], use: [// Loader 'style-loader',// Loader { loader: 'css-loader', options: {// html-loader } } ] }, ], noParse: [// /special-library\.js$/// ], }, // plugins: [ ], // resolve: { modules: [// array node_modules 'node_modules', path.resolve(__dirname, 'app') ], extensions: ['.js', '.json', '.jsx', '.css'],// alias: {// // 'module' 'new-module' 'module/path/file' 'new-module/path/file' 'module': 'new-module', // $ 'only-module' 'new-module' // 'module/path/file' 'new-module/path/file' 'only-module$': 'new-module', }, alias: [//alias { name: 'module',// alias: 'new-module',// // true 'module' false 'module/inner/path' onlyModule: true, } ], symlinks: true,// descriptionFiles: ['package.json'],// mainFields: ['main'],// enforceExtension: false,// }, // performance: { hints: 'warning',// hints: 'error',// hints: false,// maxAssetSize: 200000,// ( bytes) maxEntrypointSize: 400000,// ( bytes) assetFilter: function(assetFilename) {// return assetFilename.endsWith('.css') || assetFilename.endsWith('.js'); } }, devtool: 'source-map',// source-map context: __dirname,//Webpack string // target: 'web',// target: 'webworker',//WebWorker target: 'node',//Node.js `require` Chunk target: 'async-node',//Node.js Chunk target: 'node-webkit',//nw.js target: 'electron-main',//electron, target: 'electron-renderer',//electron, externals: {// JavaScript jquery: 'jQuery' }, stats: {// assets: true, colors: true, errors: true, errorDetails: true, hash: true, }, devServer: {//DevServer proxy: {// '/api': 'http://localhost:3000' }, contentBase: path.join(__dirname, 'public'),// DevServer HTTP compress: true,// gzip historyApiFallback: true,// HTML5 History API hot: true,// https: false,// HTTPS }, profile: true,// Webpack cache: false,// watch: true,// watchOptions: {// // ignored:/node_modules/, // 300ms // 300ms aggregateTimeout: 300, // 1000 poll: 1000 },}

Webpack 2

  1. env
    Webpack
    env
    Object Object Webpack
    webpack --env.production --env.bao=foo
    env
    {"production":"true","bao":"foo"}
  2. argv
    Webpack
    --config
    --env
    --devtool
    webpack -h
    Webpack

webpack
webpack --env.production

  • Webpack
    entry
  • output
  • resolve
  • module
    module.rules
    Loader
  • Plugin
    plugin

babel

{ "presets": ["@vue/app"]}
  • .babelrc babel ,babel , .babelrc
  • .babelrc json , .babelrc (presets) (plugins) ,
  • plugins babel
  • Babel javascript API Iterator, Generator, Set, Maps, Proxy, Reflect,Symbol,Promise ( Object.assign)

babel-runtime es6 es5 es6 babel-runtime es5. ES6 ES6 ES5.

import Promise from 'babel-runtime/core-js/promise'//

babel-polyfill prototype Array.prototype.find polyfill, es6

babel-plugin-transform-runtime

{ 'plugins': [ [ 'transform-runtime', { 'helpers': false, 'polyfill': false, 'regenerator': true, 'moduleName': 'babel-runtime' } ] ]}
  • **helpers: true ** babel helpers( babel ) extends etc
  • polyfill true (Promise, Set, Map)
  • **regenerator true ** generator regenerator runtime
  • **moduleName babel-runtime ** module/.
  • presets Babel presets Plugins

js , plugin , Babel ES2015 Transform Plugins babel-preset-es2015 Preset .babelrc presets es2015 ES2015

//.babelrc{ "presets": [ "es2015" ]}

,babel , babel-preset-env babel-preset-latest

npm install babel-preset-env --save-dev
{ "presets": ['env']}

safari 7 polyfill

{ 'presets': [ ['env', { 'target': { 'browsers': ['last 2 versions', 'safari >= 7'] } }] ]}

babel-preset-env

  1. targets: {[string]: number | string }, {}; node
  2. targets.browsers <Array | string> browserslist
  3. modules ES6 false , commonjs
  4. loose, false preset loose
  5. include: [];
  6. exclude [];

webpack

4.0 4.0 npm

npm i webpack@3.8 -S

webpack less , webpack

  1. package.json , , webpack.

  2. "scripts": { "build": "webpack",},
  3. node_modules bin webpack , bin/webpack.js,

  4. webpack.js webpack.config.js ,

  5. npm run build

webpack.config.js

//webpack commonjs let path = require('path'); // // // path.resolve('./dist')module.exports = { entry:'./src/main.js', //,webpack , output:{ filename:'bundle.js', // path:path.resolve('./dist') // }}

entry ,

entry:{main:'.xx',main2:'xxx'} ----------------------------------- filename:'[name,name2].js'

-> npm run build

1. ,

es6 es5

babel es6 -> es5

babel

npm install babel-core --save-dev ->babel npm install babel-loader --save-dev ->

bable-loader ->webpack.config.js

// //- js js babel-loader node_modules module:{ rules:[ {test:/\.js$/,use:'babel-loader',exclude:/node_modules/} // ] }

, babel-preset-es2015 loader es6

npm i babel-preset-es2015 --save-dev

-> .babelrc

{ "presets": ["es2015"]}

es2017

es2017

npm i babel-preset-stage-0 --save-dev

.babelrc

{ "presets": ["es2015","stage-0"]}

css

css , webpack

import './xxx.css' ->

,

npm i css-loader --save-dev -> css npm i style-loader --save-dev -> style

webpack.config.js

rules//use {test:/\.css$/,use:['style-loader','css-loader']}

css -> less,sass,stylus

less-loader -> less css-loader -> style-loader sass-loader stylus-loader

less-loader less

npm i less less-loader --save-dev

rules ->webpack.config.js

{test:/\.less$/,use:['style-loader','css-loader','less-loader']}

file-loader url-loader// file-loader ,

npm i file-loader url-loader --save-dev

, base-64, ?limit=8192

base-64 8192 ,

{test:/\.(jpg|png|gif)$/,use:'url-loader?limit=8192'},

url js url , url-loader

img.src = './1.jpg' -> ,

html

html , , html , dist .

npm i html-webpack-plugin --save-dev

,

let HtmlWebpackPlugin = require('html-webpack-plugin');

plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html', //, html js filename:'login.html' // })]

, , , ( , ),

npm i webpack-dev-server --save-dev

package.json

"scripts": { "build": "webpack", "dev": "webpack-dev-server"},

npm run dev ->

webpack 3.6 ,webpack-dev-server 2.x ,

D:\myProjectDemos\webpackDemo\node_modules\ajv-keywords\keywords\instanceof.js:52 throw new Error('invalid "instanceof" keyword value ' + c); ^ Error: invalid "instanceof" keyword value Promise

8080, index.html

npm run dev -----------------------------Project is running at http://localhost:8080/

http://localhost:8080/ index.html

webpack

eslint

ESlint

.eslintrc
JSON

{ // eslint:recommended "extends": "eslint:recommended", // "rules": { // ; "semi": ["error", "always"], // "" "quotes": ["error", "double"] }}

eslint-loader ESLint Webpack

module.exports = { module: { rules: [ { test: /\.js$/, //node_modules exclude:/node_modules/, loader: 'eslint-loader', // eslint-loader Loader eslint-loader enforce: 'pre', }, ], },}

Git Git Hook

husky husky Npm Script Hook Git Hook

package.json

{ "scripts": { // git commit "precommit": "npm run lint", // git push "prepush": "lint", // eslint stylelint "lint": "eslint && stylelint" }}

webpack js , loader , , .js , webpack.config.js , module rules .

{ module:{ rules:[ { test:/\.js$/, //js , use:['babel-loader'], //bebel-loader , js , include:path, // exclude:path,// }, { test:/\.css$/, use:['style-loader','css-loader'] // loader } ] }}