[Translation] webpack official website documentation: Concepts -- 6. Configuration files

Original translation, please indicate the source when reprinting. 

Original address: https://webpack.js.org/concepts/plugins/

 

 

You may have noticed that very few webpack config files look exactly the same. This is because a webpack configuration file is a JavaScript file that exports an object. Webpack handles this object according to the properties it defines.

Since it's a standard Node.js CommonJS module, you can do something like:

  • Import other files with require(...)
  • Use utilities on npm with require(...)
  • Use JavaScript control flow expressions, namely the ?: operator
  • Define constants or variables for some frequently used values
  • Make and execute a function to generate a part of the configuration

These properties can be used as appropriate.

 

You should not do the following. It is technically possible to use them, but not recommended.

  • When using the webpack CLI , use the CLI parameter (write your own CLI , or use --env )
  • output some indeterminate value (call webpack twice, should produce the same output file)
  • Write a long configuration file (you can split the configuration file into several files)

 

The code below shows how to make a webpack configuration file clear and rich.

 

Simplest configuration

webpack.config.js

 

var path =require('path');
 
module.exports ={
  entry:'./foo.js',
  output:{
    path: path.resolve(__dirname,'dist'),
    filename:'foo.bundle.js'
  }
};

 

 

multiple goals

 

var path =require('path');
var webpack =require('webpack');
var webpackMerge =require('webpack-merge');
 
var baseConfig ={
  target:'async-node',
  entry:{
    entry:'./entry.js'
  },
  output:{
    path: path.resolve(__dirname,'dist'),
    filename:'[name].js'
  },
  plugins:[
    newwebpack.optimize.CommonsChunkPlugin({
      name:'inline',
      filename:'inline.js',
      minChunks:Infinity
    }),
    newwebpack.optimize.AggressiveSplittingPlugin({
        minSize:5000,
        maxSize:10000
    }),
  ]
};
 
let targets =['web','webworker','node','async-node','node-webkit','electron-main'].map((target)=>{
  let base =webpackMerge(baseConfig,{
    target: target,
    output:{
      path: path.resolve(__dirname,'dist/'+ target),
      filename:'[name].'+ target +'.js'
    }
  });
  return base;
});
 
module.exports = targets;

 

 

Use TypeScript

In the following example we use TypeScript to make a class through which Angluar-cli can generate configuration files.

 

webpack.config.ts

 

import* as webpackMerge from 'webpack-merge';
import{ CliConfig } from './config';
import{
  getWebpackCommonConfig,
  getWebpackDevConfigPartial,
  getWebpackProdConfigPartial,
  getWebpackMobileConfigPartial,
  getWebpackMobileProdConfigPartial
} from './';
 
exportclassNgCliWebpackConfig{
  // TODO: When webpack2 types are finished let's replace all these any types
  // so this is more maintainable in the future for devs
  public config:any;
  private webpackDevConfigPartial:any;
  private webpackProdConfigPartial:any;
  private webpackBaseConfig:any;
  private webpackMobileConfigPartial:any;
  private webpackMobileProdConfigPartial:any;
 
  constructor(public ngCliProject:any,public target:string,public environment:string, outputDir?:string){
    const config: CliConfig = CliConfig.fromProject();
    const appConfig = config.config.apps[0];
 
    appConfig.outDir = outputDir || appConfig.outDir;
 
    this.webpackBaseConfig =getWebpackCommonConfig(this.ngCliProject.root, environment, appConfig);
    this.webpackDevConfigPartial =getWebpackDevConfigPartial(this.ngCliProject.root, appConfig);
    this.webpackProdConfigPartial =getWebpackProdConfigPartial(this.ngCliProject.root, appConfig);
 
    if(appConfig.mobile){
      this.webpackMobileConfigPartial =getWebpackMobileConfigPartial(this.ngCliProject.root, appConfig);
      this.webpackMobileProdConfigPartial =getWebpackMobileProdConfigPartial(this.ngCliProject.root, appConfig);
      this.webpackBaseConfig = webpackMerge (this.webpackBaseConfig, this.webpackMobileConfigPartial);
      this.webpackProdConfigPartial = webpackMerge (this.webpackProdConfigPartial, this.webpackMobileProdConfigPartial);
    }
 
    this.generateConfig();
  }
 
  generateConfig():void{
    switch(this.target){
      case"development":
        this.config =webpackMerge(this.webpackBaseConfig,this.webpackDevConfigPartial);
        break;
      case"production":
        this.config =webpackMerge(this.webpackBaseConfig,this.webpackProdConfigPartial);
        break;
      default:
        thrownewError("Invalid build target. Only 'development' and 'production' are available.");
        break;
    }
  }
}

 

 

Using JSX

The following example uses JSX ( React JavaScript Markup ) and Babel to make a JSON configuration file that webpack understands .

import h from'jsxobj';
 
// example of an imported plugin
const CustomPlugin = config =>({
  ...config,
  name:'custom-plugin'
});
 
exportdefault(
  <webpack target="web" watch>
    <entry path="src/index.js"/>
    <resolve>
      <alias {...{
        react:'preact-compat',
        'react-dom':'preact-compat'
      }}/>
    </resolve>
    <plugins>
      <uglify-js opts={{
        compression:true,
        missing: false
      }}/>
      <CustomPlugin foo="bar"/>
    </plugins>
  </webpack>
);

 

-- End --

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326816371&siteId=291194637