Entry
Entry is the entry to the configuration module. The first step in webPack construction will start from the entry to search and iterate through all the modules that the entry depends on.
Entry is mandatory. Otherwise, webPack will exit with an error
context
Webpack finds the root directory of the file, which must be a string of absolute paths, and can also set context,context, by starting Webpack with the parameter webpack –context This affects the actual files to which the relative paths of these Entry files and dependent modules point.
The type of entry
string | ‘./app/entry’ | The file path of the entry module, which can be a relative path. |
---|---|---|
array | [‘./app/entry1’, ‘./app/entry2’] | The file path of the entry module, which can be a relative path. |
object | { a: ‘./app/entry-a’, b: [‘./app/entry-b1’, ‘./app/entry-b2’]} | Configure multiple entries and generate one Chunk for each entry |
When used with the output.library configuration item, only the module with the last entry file in the array is exported.
Chunk
Webpack assigns a name to each Chunk. The name of the Chunk depends on the configuration of Entry:
- if
entry
Is astring
或array
, only one Chunk is generated, and the name of Chunk ismain
; - if
entry
Is aobject
, there may be multiple chunks, in which case the name of Chunk isobject
The name of a key in a key-value pair.
Configuring Dynamic Entry
// synchronization function
entry: () = > {
return {
a:'./pages/a'.b:'./pages/b',}};// Asynchronous functions
entry: () = > {
return new Promise((resolve) = >{
resolve({
a:'./pages/a'.b:'./pages/b'}); }); };Copy the code
Output
Output configures how to output the final desired code. Output is an object that contains a series of configuration items, which are described below.
filename
Filename Specifies the name of the configuration output file. The value is a string. If there is only one output file, it can be written statically invariant
filename: 'bundle.js'
Copy the code
But when you have multiple chunks to export, you need to use templates and variables. Webpack assigns a name to each Chunk. You can use the name of the Chunk to distinguish the filename of the output:
filename: '[name].js'
/** * id Unique identifier of Chunk, Hash hash value unique identifier of Chunk. Chunkhash Hash value of Chunk content. // The length of hash and chunkhash can be specified. [hash:8] indicates the 8-bit hash value. The default value is 20 bits /Copy the code
The [name] in the code stands for replacing [name] with the built-in name variable, which you can think of as a string module function that concatenates the name of the output file for each Chunk to be exported
chunkFilename
The name of a chunk file that is not included in the entry but needs to be packaged out. In general, this chunk file refers to code that is lazy to load
path
Path Specifies the local directory where the output file is stored. The path must be an absolute string path. The absolute path is usually obtained from the Node.js path module:
path: path.resolve(__dirname, 'dist_[hash]')
Copy the code
publicPath
Output. publicPath Configures the URL prefix published to online resources, which is of string type. The default is an empty string “, that is, a relative path. In short, configure the default prefix
filename:'[name]_[chunkhash:8].js'
publicPath: 'https://cdn.example.com/assets/'
Copy the code
Both output.path and output.publicPath support string templates with only one built-in variable: hash represents the hash value of a compilation operation
crossOriginLoading
The output. CrossOriginLoading is used to configure the asynchronous crossorigin value of the insert TAB.
The Crossorigin attribute of the script tag can take the following values:
anonymous
(Default) This script resource is loaded without the user’s Cookies;use-credentials
The user’s Cookies are loaded with this script resource.
It is common to set crossorigin to get detailed error information about the execution of asynchronously loaded scripts.
LibraryTarget and library
The purpose of this configuration is to control how webpack packaged content is exposed and to address the compatibility of different introductions when packaged files are used.
output.library
Configure the name of the export library.output.libraryTarget
Configures how to export the library, which is an enumeration type of string that supports the following configuration- Var (default) When a library (packaged via Webpack) is loaded, the return value of the library is assigned to use
var
Library is equivalent to a global variable named output.library - Commonjs is exported through the CommonJS specification to define variables for library Settings on the export object. Supported in Node, not in browser.
- Commonjs2: export from module.export ignores library variables. Supported in Node, not in browser
- Amd, which defines variables set by the library in the define method, cannot be referenced directly by script and must be used via the third-party module RequireJS
- Umd, this scheme supports CommonJS, CommonJS2, AMD, can be common in browser, node. But if you want to do this, you have to set something else, umdNamedDefine: True, globalObject: ‘this’,
- Var (default) When a library (packaged via Webpack) is loaded, the return value of the library is assigned to use
Module
Module configures how to handle modules. Webpack treats all files as modules, and CSS files are no exception. Importing main. CSS is like importing JavaScript files because Webpack doesn’t natively support parsing CSS files. To support non-javascript types of files, you need to use the Loader mechanism of Webpack
rules
Rules Configures the read and parse rules of the module and is usually used to configure the Loader. The type is an array, and each item in the array describes how to process part of the file. The following describes how to configure a rule
- Conditional match: Yes
test
、include
、exclude
Three configuration items to match the file to which the Loader applies the rule. - Application rule: Pass the selected file
use
To apply loaders, you can apply only one Loader or a group of Loaders in sequential order, and pass parameters to Loaders respectively. - Reset order: A group of Loaders executes from right to left by default
enforce
Option to place the execution order of one Loader first or last
module: {
rules: [{// Hit JavaScript files
test: /\.js$/.// Use babel-loader to convert JavaScript files
/ /? CacheDirectory represents a parameter passed to babel-loader to cache Babel compilation results to speed recompilation
use: ['babel-loader? cacheDirectory'].// Only hit js files in SRC directory to speed up Webpack search
include: path.resolve(__dirname, 'src')}, {// Hit the SCSS file
test: /\.scss$/.// Use a set of loaders to process SCSS files.
// The processing sequence is from back to front, that is, the sass-loader submits the result to CSS-loader, and then to style-loader.
use: ['style-loader'.'css-loader'.'sass-loader'].// Exclude files in node_modules
exclude: path.resolve(__dirname, 'node_modules'),}, {// Use file-loader to load non-text files
test: /\.(gif|png|jpe? g|eot|woff|ttf|svg|pdf)$/,
use: ['file-loader'],},]}Copy the code
If the Loader needs to pass many parameters, you can also use an Object to describe it. For example, in the babel-loader configuration above, there is the following code:
use: [
{
loader:'babel-loader'.options: {cacheDirectory:true,},// Enforce :'post' means to place the execution order of the Loader at the end
// Enforce can also be pre, indicating that the execution order of the Loader is put first
enforce:'post'
},
// omit other loaders
]
Copy the code
In the example above, the test include exclude configuration items that match the file are passed in only a string or regular. They also support an array type, as follows:
{
test: [/\.jsx? $/./\.tsx? $/].include:[
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'tests')],exclude:[
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'bower_modules')]}Copy the code
Each item in the array is an or relationship, that is, the file path matches any of the criteria in the array will be hit.
noParse
The noParse configuration item allows Webpack to ignore recursive parsing and processing of portions of files that are not modularized, which has the benefit of improving build performance
NoParse is optional. The type of noParse must be RegExp, [RegExp], or function.
/ / use regular expressions noParse: / jquery | chartjs / / / using the function, from Webpack 3.0.0 began supporting noParse: (content) = > {/ / content on behalf of a module file path / / return true or false return/jquery | chartjs /. The test (content); }
Copy the code
parser
Configure modular JavaScript parsing. The Parser attribute provides a more fine-grained configuration of which module syntax to parse and which not to parse
module: { rules: [{test: /\.js$/, use: ['babel-loader'].parser: { amd: false.// Disable AMD CommonJS: false, // disable COMMONJS system: false, // disable SystemJS harmony: // Disable ES6 import/export requireInclude: false, // disable require.include requireEnsure: // Disable require.context browserify: false, // disable browserify requireJs: False, // Disable requirejs}},]}
Copy the code
Resolve
Resolve configuates Webpack how to find files for modules. Webpack has built-in JavaScript modularization syntax parsing. The default rules are set in the modularization standard, but you can change the default rules to suit your needs
alias
The resolve.alias configuration item maps the original import path to a new one using an alias. For example, use the following configuration:
// Webpack alias resolve:{alias:{components: './ SRC /components/'}}// The above alias configuration means to replace the components keyword in the import statement with./ SRC /components/.
Copy the code
When you import Button from’ components/ Button ‘, the alias is essentially replaced by import Button from’./ SRC /components/ Button ‘.
resolve:{ alias: {'react$': '/path/to/react.min.js' }}//react$will only hit import statements ending with react, i.e., replace import 'react' keyword with import '/path/to/react.min.js'.
Copy the code
mainFields
When importing a module from an NPM package (for example, import * as D3 from “D3”), this option determines which field to use in package.json to import the module. The default value varies depending on the target specified in the WebPack configuration
mainFields: ["module"."main"]// For example, D3 package.json contains these fields: {... main: 'build/d3.Node.js', browser: 'build/d3.js', module: 'index', ... }
Copy the code
This means that when we import * as D3 from “D3”, we actually parse the file from the browser property. The Browser property is preferred here because it is the first entry of mainFields. Meanwhile, Node.js applications packaged with WebPack parse files from the Module field by default.
Webpack will decide which environments of code to use third-party modules in preference to mainFields’ configuration,
MainFields: ['browser', 'main'] mainFields: ['browser', 'main']
Copy the code
extensions
When an import statement does not have a file suffix, Webpack automatically adds the suffix and tries to access the file. The resolve.extensions are used to configure the list of suffixes to use during the attempt. The default is:
extensions: ['.js'.'.json']
Copy the code
This means that when an import statement such as require(‘./data’) is encountered, Webpack will first look for the./data.js file, then look for the./data.json file if it doesn’t exist, and then report an error if it still can’t find it.
modules
Resolve. modules configures the directory in which Webpack looks for third-party modules, and by default only node_modules. Sometimes there are modules in your project that are heavily dependent on and imported by other modules. Since the location of other modules is variable, the relative path of the imported module file must be calculated for different files. This path can be very long, like this: import ‘.. /.. /.. /components/button’ At this point you can optimize with the modules configuration item, if the bulk of the imported modules are in the./ SRC /components directory, set modules to
modules:['./src/components'.'node_modules']// After that, you can simply import 'button'.
Copy the code
descriptionFiles
Resolve. DescriptionFiles Configures the name of the file that describes the third-party module, that is, the package.json file. The default is as follows:
descriptionFiles: ['package.json']
Copy the code
enforceExtension
When enforceExtension is set to true, all import statements must have file suffixes; for example, when import ‘./foo’ is enabled, it works properly; when enforceExtension is enabled, it must be written import ‘./foo.js’.
enforceModuleExtension
EnforceModuleExtension and enforceExtension work similarly, But enforceModuleExtension only applies to modules under node_modules, and enforceModuleExtension is usually used with enforceExtension, In enforceExtension: true, because most of third-party modules installed import statements don’t have my file suffix, so at this time by configuring enforceModuleExtension: false to compatible with third-party modules.
Plugin
Plugin is designed to extend Webpack functionality by injecting hook implementations into the build process, which gives Webpack a lot of flexibility.
Configure the Plugin
Plugins take an array of items, each of which is an instance of the Plugin to be used. The plugins’ parameters are passed in through the constructor
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');module.exports = { plugins: [ // New CommonsChunkPlugin({name: 'common', chunks: ['a', 'b']}),]};
Copy the code
DevServer
DevServer will start an HTTP server to service web requests, and it will help start Webpack, receive the signal of file changes sent by Webpack, and automatically refresh the web page through WebSocket protocol to achieve real-time preview.
- Provide HTTP services instead of using local file previews;
- Monitor the changes of files and automatically refresh the web page to achieve real-time preview;
- Source Map is supported for easy debugging.
npm i -D webpack-dev-server
Copy the code
After the installation is successful, run the webpack-dev-server command to start DevServer
Package. The json increase script
"dev": "webpack-dev-server"
Copy the code
Note: “webpack – dev – server” : “^ 3.11.2” + “webpack – cli” : “^ 3.3.12”,
hot
Devserver. hot Configures whether to enable the module hot replacement function. The default behavior of DevServer is to preview in real time by automatically refreshing the entire page when the source code has been updated. With module hot replacement enabled, it will preview in real time by replacing old modules with new ones without refreshing the entire page.
inline
DevServer’s live preview relies on a proxy client injected into the page to receive commands from DevServer and refresh the page. Devserver. inline configures whether the proxy client is automatically injected into the Chunk that will run on the page. The default is automatic injection. DevServer adjusts its auto-refresh policy depending on whether you have inline enabled or not:
- If open
inline
, DevServer controls the page refresh through the proxy client as the changed code is built. - If you shut down
inline
, DevServer will have no direct control over the web pages to be developed. It then runs the web page as an iframe and refreshes the iframe to preview the changes in real time when the code is built. But then you need to gohttp://localhost:8080/webpack-dev-server/
Preview your web page in real time now.
If you want to use DevServer to automatically refresh web pages for live preview, the most convenient way is to turn inline on directly.
historyApiFallback
Whether to enable the multi-page application
Configure multiple pages
historyApiFallback: { HTML {from: /^\/user/, to: '/user.html'}, {from: /^ /game/, to: '/ game. HTML}, / / other return index. The HTML {the from: /. /, to:'/index. HTML},]}
Copy the code
contentBase
Devserver. contentBase Configures the root directory of the devServer HTTP server. The default is the current execution directory, unless you have additional files that need to be served by DevServer. For example, if you want to set the public directory in the project root directory to the DevServer root directory, you can do this:
devServer:{ contentBase: path.join(__dirname, 'public')}
Copy the code
headers
The devServer.headers configuration item can inject HTTP headers into an HTTP response using the following:
devServer:{ headers: { 'X-foo':'bar' }}
Copy the code
host
The devServer.host configuration item configures the IP address listened by the devServer service. For example, if you want other devices on the LAN to access your local service, start DevServer with –host 0.0.0.0. The default value for host is 127.0.0.1, which means that only local users can access DevServer’s HTTP service
port
Devserver. port Configures the port monitored by devServer. By default, port 8080 is used. If port 8080 is already occupied by another program, use 8081, if 8081 is still occupied, use 8082, and so on.
allowedHosts
AllowedHosts: devServer.allowedHosts: whitelisted: only HTTP hosts in the whitelisted list are returned as follows:
allowedHosts: [ // Match single domain 'host.com', 'sub.host.com', // host2.com and all subdomains *.host2.com will match '.host2.com']
Copy the code
https
DevServer uses HTTP by default, and it can also use HTTPS. In some cases you must use HTTPS, for example HTTP2 and the Service Worker must run on HTTPS. The easiest way to switch to HTTPS is:
devServer:{ https: true}
Copy the code
DevServer will automatically generate an HTTPS certificate for you. If you want to use your own certificate you can configure it like this:
devServer:{ https: { key: fs.readFileSync('path/to/server.key'), cert: fs.readFileSync('path/to/server.crt'), ca: fs.readFileSync('path/to/ca.pem')}}Copy the code
open
Devserver. open is used to automatically open the web page you want to develop with the default browser on your system when devServer starts and the first build is finished. The devServer.openPage configuration item is also provided to open a web page at the specified URL.
Target
The Target configuration allows Webpack to build code for different runtime environments
The target value | describe |
---|---|
web |
For browsers(the default)All the code in one file |
node |
For Node.js, use therequire Statement loads Chunk code |
async-node |
For Node.js, load Chunk code asynchronously |
webworker |
In view of the WebWorker |
electron-main |
forElectronThe main thread |
electron-renderer |
For the Electron render thread |
For example, when you set target:’node’, the source code statement require(‘fs’) importing the node.js native module will be retained, and the fs module’s contents will not be packaged into Chunk.
Devtool
Devtool configures how the Source Map is generated by Webpack. The default value is false, which means that the Source Map is not generated.
module.export = { devtool: 'source-map'}
Copy the code
Watch and WatchOptions
Webpack’s listening mode, which allows you to listen for file updates and recompile when the file changes. Listening mode is turned off by default when using Webpack. To turn it on you need to do the following
module.export = { watch: true}
Copy the code
When DevServer is used, the listening mode is turned on by default.
In addition, Webpack also provides the watchOptions configuration to control the listening mode more flexibly, using the following:
module.export = { WatchOptions are valid only if watchmode is enabled // Default is false (watch: true is not enabled) // watchOptions are valid only if watchmode is enabled: {// Files or folders that are not listened on. Regular matching is supported. // Empty by default: // the default value is 300ms aggregateTimeout: // the default value is 300ms aggregateTimeout: Poll: 1000} // Poll: 1000} // poll: 1000}
Copy the code
Externals
Externals is used to tell Webpack which modules are used in the code to build that need not be packaged, meaning that these templates are provided by the external environment and Webpack can ignore them when packaging.
Some JavaScript runtime environments may have global variables or modules built in, such as in your HTML HEAD tag:
<script src="path/to/jquery.js"></script>
Copy the code
Externals can be used to tell Webpack that the JavaScript runtime environment already has global variables built into it, so you don’t need to package them into your code and use them directly. To solve this problem, you can configure externals like this:
module.export = { externals: { Jquery: 'jquery'}}
Copy the code
ResolveLoader
ResolveLoader is used to tell Webpack how to find the Loader. Since the Loader is referenced by its package name, Webpack needs to find the actual Loader code according to the configured Loader package name. To call Loader to process the source file.
ResolveLoader’s default configuration is as follows:
module.exports = { resolveLoader: {// Loader modules: ['node_modules'], // Extensions: ['.js', '.json'], // mainFields: ['loader', 'main'] }}
Copy the code
Overall configuration structure
const path = require('path');module.exports = { // Entry represents the entry, and Webpack performs the first step of the build from entry, which can be abstracted as input. / / type can be a string | object | array entry: '/ app/entry', / / only one entrance, entrance only one file entry: ['/app/entry1 ', '/ app/entry2'], / / only one entrance, the entrance there are two file entry: {/ / have two entrance to a: '/ app/entry - a', b: ['./app/entry-b1', './app/ entry-B2 ']}, // How to output the result: how to output the final desired code after a series of processing in Webpack. Output: {// The directory where the output file is stored. It must be an absolute path of type string. Resolve (__dirname, 'dist'), // Output file filename: 'bundle.js', // full name filename: '[name].js', // When multiple entries are configured, use the name template to generate different file names for different entries filename: '[chunkhash].js', // Generate the file name based on the hash value of the file content, used by the browser to cache the file for a long time // The URL prefix of all resources published online, string publicPath: '/assets/', // to the specified directory publicPath: '", // to the root directory publicPath: 'https://cdn.example.com/', // to the CDN // the name of the export library, string type // without it, the default output format is the anonymous execute now function library: 'MyLibrary', // Export library type, enumeration type, The default is/var/can be umd | umd2 | commonjs2 | commonjs | | amd this | var | assign window | | global | json, libraryTarget: 'umd', // whether to include useful file path information to the generated code, Boolean type pathInfo: true, // The name of the additional Chunk file chunkFilename: '[id].js', chunkFilename: '[chunkhash].js', // JSONP async load resource callback function name, need to use jsonpFunction with server: 'myWebpackJsonp', // Generated Source Map file name sourceMapFilename: '[file]. The map', / / the browser in the developer tools shows the source module name devtoolModuleFilenameTemplate: 'webpack:///[resource-path]', // How to load cross-domain resources asynchronously crossOriginLoading: 'use-credentials', crossOriginLoading: 'anonymous', crossOriginLoading: false,}, // Configure module related module: {rules: [// configure Loader {test: Resolve (__dirname, 'app')], exclude: /\.jsx?$/, // include: [// Path. resolve(__dirname, 'app/demo-files')], use: [// use Loader in sequence, execute 'style-loader' from back to front, // use Loader name directly {Loader: 'css-loader', options: {// Pass some parameters to html-loader}}]},], noParse: [// do not parse the module /special-library\.js$/ / with re matching],}, // configure plugins: [], // configure the rule to find modules resolve: {modules: [// find the root directory of the module, array type, default node_modules root directory 'node_modules', path.resolve(__dirname, 'app')], extensions: ['. Js', 'json', 'JSX', 'CSS'], / / module suffix alias: {// module alias configuration, used to map modules // map 'module' to 'new-module', the same 'module/path/file' will be mapped to 'new-module/path/file' 'module': 'new-module', // map 'only-module' to 'new-module' with the ending $, // But unlike above, 'module/path/file' will not be mapped to 'new-module/path/file' 'only-module$': 'new-module',}, alias: [// alias also supports arrays for more detailed configuration {name: 'module', // The old module alias: 'new-module', // new module/ / whether only modules will be mapped, if true only 'module' will be mapped, if false 'module/inner/path' will be mapped onlyModule: }], symlinks: true, // Whether to follow the soft link to find the module's path descriptionFiles: ['package.json'], // mainFields: ['main'], // whether the enforceExtension statement is mandatory, and the file suffix is enforceExtension: false, // Whether the enforceExtension statement must be enforceExtension}, // Output file performance check configuration Performance: {hints: Hints: 'error', // Displays warning hints: 'error', // displays error hints: False, // Turns off performance check maxAssetSize: 200000, // Maximum file size (bytes) maxEntrypointSize: 400000, // Maximum entry file size (bytes) assetFilter: Function (assetFilename) {/ / filter file to check the return assetFilename. EndsWith (' CSS ') | | assetFilename. EndsWith (' js'); }}, devtool: 'source-map', // configure source-map context: __dirname, // the root directory used by Webpack, string must be the absolute path // Configure the running environment of the output code target: 'web', // browser, default target: 'webworker', // webworker target: 'node', // node. js, load Chunk code target with 'require' statement: 'async-node', // node. js, async load Chunk code target: 'node-webkit', // nw.js target: 'electron ', // electron, main thread target: 'electron-renderer', // electron, render thread externals: {// Use global variables provided by the JavaScript runtime environment jquery: 'jquery', stats: {// Console output log control assets: true, colors: true, errors: True, errorDetails: true, hash: true,}, devServer: {// DevServer-related configuration proxy: {// Proxy to back-end service interface '/ API ': 'http://localhost:3000'}, contentBase: path.join(__dirname, 'public'), // configure DevServer HTTP server root directory compress: HistoryApiFallback: true, // Whether to enable gzip historyApiFallback: true, // Whether to develop HTML5 History API pages hot: true, // Whether to enable module hot replacement HTTPS: False, // whether to enable HTTPS mode}, profile: true, // Whether to capture Webpack build performance information to analyze the cause of poor build performance Cache: false, // Whether to enable caching to improve build speed watch: True, // Whether to start watchOptions: {// Listen mode options // do not listen to files or folders, support regular matching. Ignored: /node_modules/. // aggregateTimeout: 300ms. // aggregateTimeout: 300ms. Poll: 1000}, poll: 1000}, poll: 1000}
Copy the code
Multiple Environment Configurations
When you run Webpack, you pass two arguments to this function:
env
: WebPack-specific environment variable of the current runtime,env
Is an Object. Read directly to the properties of Object, which need to be set with parameters when starting Webpack. For example, the start command iswebpack --env.production --env.bao=foo
When,env
The value is{"production":"true","bao":"foo"}
.argv
: represents all arguments passed through the command line when Webpack is started, for example--config
,--env
,--devtool
, can be accessed throughwebpack -h
Lists all command line arguments supported by Webpack.
For the configuration files above, execute webpack at development time to build code that is easy to debug, and execute webpack –env.production to build compressed code when you need to build code that is published online.
Configuration summary
- Want source files added to the build process to be controlled and configured by Webpack
entry
. - To customize the location and name of the output file, configure
output
. - To customize the policy for finding dependent modules, configure
resolve
. - Want to customize the policy for parsing and converting files, configure
module
, usually configurationmodule.rules
In the Loader. - Most of the other requirements may have to be configured via Plugin
plugin
.
Babel configuration
{ "presets": ["@vue/app"]}
Copy the code
- .babelrc is an extension of Babel, which reads the configuration from the project’s root directory
- .babelrc is a JSON file. In the.babelrc configuration file, presets and plugins are configured.
- Plugins tell Babel which plug-ins to use, and these plug-ins control how the code is transformed.
- Babel by default only converts new javascript syntax, not new apis, such as Iterator, Generator, Set, Maps, Proxy, Reflect,Symbol,Promise, and other global objects. And some methods on global objects (such as Object.assign) do not transcode.
Babel-runtime which compiles ES6 to ES5 for execution. We write it using ES6 syntax and will eventually compile to ES5 via babel-Runtime. That is, regardless of whether the browser supports ES6, as long as the ES6 syntax, it will transcode to ES5. So there’s a lot of redundant code.
import Promise from 'babel-runtime/core-js/promise'// This not only avoids contaminating global objects, but also reduces unnecessary code.
Copy the code
Babel-polyfill is implemented by adding methods to the prototype of both the global object and the built-in object. For example, array.prototype. find is not supported in the runtime environment, so we can use ES6 method to write polyfill, but the disadvantage is that it will cause global space pollution.
babel-plugin-transform-runtime
{ 'plugins': [ [ 'transform-runtime', { 'helpers': false, 'polyfill': false, 'regenerator': true, 'moduleName': 'babel-runtime' } ] ]}
Copy the code
- **helpers: The default value is true. ** indicates whether inline Babel helpers such as extends and etc are enabled when module names are called.
- Polyfill: Defaults to true and indicates whether built-in things (Promise, Set, Map) are converted to non-globally polluted.
- ** reGenerator: The default value is true, ** Whether to enable generator function conversion to use ReGenerator Runtime to avoid global contamination.
- ModuleName: Defaults to babel-Runtime, and sets the module name/path when called.
- Presets, a collection of Plugins, tell Babel what new syntaxal features are being used in the source code to be transformed.
There are multiple PLUGIN Plugins in one version of JS syntax, but the Babel team gathered dozens of Transform Plugins belonging to ES2015 into babel-preset- ES2015 one preset, for convenience. We only need to add an ES2015 configuration to the. Babelrc presets to complete the es2015 syntax support:
// .babelrc{ "presets": [ "es2015" ]}
Copy the code
As versions of Babel become more accurate over time, babel-preset-env comes in, which functions like babel-preset-latest, choosing new features that are not supported by the target environment to be preset
First you need to install it in your project with the following command:
npm install babel-preset-env --save-dev
Copy the code
{ "presets": ['env']}
Copy the code
If we need to support polyfill code conversions required for the last two versions of each browser and safari 7 or greater, we can configure the following:
{ 'presets': [ ['env', { 'target': { 'browsers': ['last 2 versions', 'safari >= 7']]]}}}Copy the code
Understand the option configuration in babel-preset-env:
- The targets: {[string] : number | string}, the default is {}; Objects that support a runtime environment, such as node versions;
- The targets. Browsers < Array | string > support browser configuration items, the ways configuration items used to browserslist query
- Modules Enables the conversion of ES6 module syntax to another module type. Set this to false to not convert modules, default commonJS
- Loose, this parameter is false by default. Meaning: allow them to enable the “loose” transformation for any plug-in for this preset.
- Include: includes some plug-ins, default is []; For example, including arrow functions,
- Exclude. Which plug-ins are excluded? The default is [];
Install webpack
Now the default is version 4.0 and my notes are that versions below 4.0 can be specified in the NPM installation
NPM [email protected] - I SCopy the code
It is best not to install webPack or less globally, otherwise it may cause webPack version differences
-
Configure a script in package.json that uses the command webpack.
-
"scripts": { "build": "webpack",}, Copy the code
-
Node_modules: bin/webpack.js
-
Webpack. js requires a file in the current directory called webpack.config.js,
-
The directory in which we execute the NPM run build is the directory of the current folder so we will look it up in the current directory
Webpack.config.js packages the configuration
// webpack must use commonJS let path = require('path'); Path.resolve ('./dist')module.exports = {entry:'./ SRC /main.js', Output :{filename:'bundle.js', Resolve ('./dist') // Must be the absolute path to pack the file where}}Copy the code
Writing fixed
You need to package multiple so you write one object in entry multiple entries, and you write an array in exit
entry:{main:'.xx',main2:'xxx'} ----------------------------------- filename:'[name,name2].js'
Copy the code
Package command -> NPM run build
1. Solve module problems package multiple modules into a file, and do not need to manage various module specifications
Turn es6 es5
Babel escapes ES6 -> es5
Install Babel
NPM install babel-core --save-dev -> Babel core NPM install babel-loader --save-dev -> parsing moduleCopy the code
Configuration bable – loader – > webpack. Config. Js
Node_modules module:{rules:[ {test: / \. Js $/, use: 'Babel - loader, exclude: / node_modules /} / / use a regular file matching]}Copy the code
Install babel-preset- ES2015 to tell loader that it has the syntax to parse ES6
Install NPM I babel-preset- ES2015 --save-devCopy the code
Create a new file in the current directory with a fixed name ->.babelrc
{ "presets": ["es2015"]}
Copy the code
Parse es2017 syntax
Download the es2017 plug-in first
npm i babel-preset-stage-0 --save-dev
Copy the code
And then. Babelrc configuration
{ "presets": ["es2015","stage-0"]}
Copy the code
Parsing CSS styles
Import CSS files, such import operations webpack cannot parse
Import './xxx. CSS '-> this introduces no recognitionCopy the code
You need to download the plug-in first,
NPM I style-loader --save-dev -> Insert the parsed content into the style tagCopy the code
Then configure the rules in webpack.config.js
{test:/\.css$/,use:['style-loader','css-loader']}Copy the code
CSS preprocessor languages -> LESS, SASS,stylus
less-loader -> less css-loader -> style-loader sass-loader stylus-loader
Install less-Loader and Less
npm i less less-loader --save-dev
Copy the code
Configuration rules – > webpack. Config. Js
{test:/\.less$/,use:['style-loader','css-loader','less-loader']}
Copy the code
Resolution images
File-loader url-loader // Using this is dependent on file-loader and will be called automatically, but will be under
npm i file-loader url-loader --save-dev
Copy the code
Add configuration, by default the image will be base-64, can I set it? limit=8192
Base-64 is converted only below 8192 bytes, otherwise output image
{test:/\.(jpg|png|gif)$/,use:'url-loader? limit=8192'},Copy the code
Write image URL directly js will not treat it as url but as character parsing, need to url-loader parsing
Img. SRC = './1.jpg' -> Attribute value is a string, which is returned when the string is parsedCopy the code
Automatically create NEW HTML and import files
The plugin uses our own HTML as a template to automatically import the packaged results into THE HTML and export them to the dist directory.
npm i html-webpack-plugin --save-dev
Copy the code
This is a plug-in that needs to be introduced in the configuration file
let HtmlWebpackPlugin = require('html-webpack-plugin');
Copy the code
And then configure
plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html', Filename :'login.html' // output filename})]Copy the code
There is a built-in service that enables us to start a port number, and when the code is updated, it is automatically packaged (no physical files are generated, in memory) and re-executed as the code changes
npm i webpack-dev-server --save-dev
Copy the code
Configure the script in package.json
"scripts": { "build": "webpack", "dev": "webpack-dev-server"},
Copy the code
You can then run NPM run dev -> to run the built-in server
If your webpack version is higher than 3.6,webpack-dev-server can only install 2.x, otherwise an error will be reported
D:\myProjectDemos\webpackDemo\node_modules\ ajV-keywords \keywords\instanceof.js:52 throw new Error('invalid ' "instanceof" keyword value ' + c); ^ Error: invalid "instanceof" keyword value PromiseCopy the code
If there is no problem, the built-in server listener port number 8080 is turned on. The default is index.html
NPM run dev start built-in server -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the Project is running at http://localhost:8080/Copy the code
The browser type http://localhost:8080/ to open index.html, which does not require a route
The basic configuration of WebPack is done
Eslint configuration
ESlint configuration file.eslintrc, in JSON format.
{ // Inherit all checking rules" extends": "eslint:recommended" from eslint:recommended", // customize some rules" rules": {// need to add at the end of each line; "Semi" : [" error ", "always"], / / need to use the string "" package" quotes ": [" error", "double"]}}
Copy the code
Eslint-loader can easily integrate ESLint into Webpack as follows:
module.exports = { module: { rules: [{test: /\.js$/.// exclude: /node_modules/, loader: Nenext: 'pre',},],},}
Copy the code
If your project is managed using Git, Git provides a Hook function that triggers the execution of scripts before committing code.
When husky is installed, it automatically configures Git hooks via Npm Script Hook. All you need to do is define a few scripts in package.json.
{ "scripts": { // The script "precommit": "NPM run lint" will be executed before git commit, // the script "prepush" will be executed before git push: "Lint ", // call eslint, stylelint, etc to check the code "lint": "eslint && stylelint"}}
Copy the code
Personal insight
First of all, Webpack can only parse JS files, so all other types of files need to be translated by the corresponding loader, which translates files with different suffixes into.js files. This process requires the rules rules under webpack.config.js configuration and module.
{ module: {rules:[ { test:/\.js$/.// Match the js suffix, use:['babel-loader'], // use bebel-loader for translation, because there may be different versions of js syntax conversion, include:path, // exclude:path, }, {test:/\.css$/, use:['style-loader','css-loader']
Copy the code