使用不同语言进行配置(Configuration Languages)

webpack 接受以多种编程和数据语言编写的配置文件。支持的文件扩展名列表,可以在 node-interpret 包中找到。使用 node-interpret,webpack 可以处理许多不同类型的配置文件。

TypeScript

To write the webpack configuration in TypeScript, you would first install the necessary dependencies:

npm install --save-dev typescript ts-node @types/node @types/webpack

and then proceed to write your configuration:

webpack.config.ts

import * as webpack from 'webpack';
import * as path from 'path';
declare var __dirname;

const config: webpack.Configuration = {

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

export default config;

CoffeeScript

Similarly, to use CoffeeScript, you would first install the necessary dependencies:

npm install --save-dev coffee-script

and then proceed to write your configuration:

webpack.config.coffee

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

config =
  entry: './path/to/my/entry/file.js'
  output:
    path: path.resolve(__dirname, 'dist')
    filename: 'my-first-webpack.bundle.js'
  module: rules: [ {
    test: /\.(js|jsx)$/
    use: 'babel-loader'
  } ]
  plugins: [
    new (webpack.optimize.UglifyJsPlugin)
    new HtmlWebpackPlugin(template: './src/index.html')
  ]

module.exports = config

Babel and JSX

In the example below JSX (React JavaScript Markup) and Babel are used to create a JSON Configuration that webpack can understand.

Courtesy of Jason Miller

First install the necessary dependencies:

npm install --save-dev babel-register jsxobj babel-preset-es2015

.babelrc

{
  "presets": [ "es2015" ]
}

webpack.config.babel.js

import jsxobj from 'jsxobj';

// example of an imported plugin
const CustomPlugin = config => ({
  ...config,
  name: 'custom-plugin'
});

export default (
  <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,
        mangle: false
      }} />
      <CustomPlugin foo="bar" />
    </plugins>
  </webpack>
);

If you are using babel elsewhere and have modules set to false, you will have to either maintain two separate .babelrc files or use const jsxobj = require('jsxobj'); and module.exports instead of the new import and export syntax. This is because while Node does support many new ES6 features, they don't yet support ES6 module syntax.


原文:https://webpack.js.org/configuration/configuration-languages/

results matching ""

    No results matching ""