webpack

什么是Webpack?

webpack.config.js

webpack配置文件(默认文件名webpack.config.js)

touch webpack.config.js

Entry

这个入口(entry)告诉webpack从哪里开始打包(bundle)。

module.exports = {
  entry: './app/index.js'
};

Output

输出配置,如何处理打包的文件。

const path = require('path');

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

Loaders

webpack将所有的文件(.css,html,.scss,.jpg等等)都当做模块(module),然而webpack只懂得JavaScript。那么,loaders在这里的作用就是将所有的文件转换为webpack理解的模块。

const path = require('path');

const config = {
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.bundle.js'
  },
  module: {
    rules: [
      {test: /\.(js|jsx)$/, use: 'babel-loader'}
    ]
  }
};

module.exports = config;

以上的这个例子是说:“Hey webpack,当你在require()/import语句中发现,以.js或者.jsx的文件时,请用babel-loader做一个转换,然后添加到bundle中去”

Plugins

插件最主要的作用是对“编译”和“分块”之后的打包文件继续做处理或者操作。

使用方法很简单:require该插件,然后放到plugins的数组中。你可以重复使用同一个插件来达到不同的目的,所以通常情况下都是new一个插件放到数组中。

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

const config = {
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.bundle.js'
  },
  module: {
    rules: [
      {test: /\.(js|jsx)$/, use: 'babel-loader'}
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({template: './app/index.html'})
  ]
};

module.exports = config;

产品代码

webpack配置完成了,现在,将下面的产品代码复制到对应的文件中去:

./app/index.html

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>React 0 to 1 Workshop</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <div id="app"></div>
</body>

</html>

./app/index.js

var textnode = document.createTextNode("Hello React 0 to 1");
document.body.appendChild(textnode);

当前的目录结构应该是:

.
├── README.md
├── app
│   ├── index.html
│   └── index.js
├── node_modules
├── package.json
├── webpack.config.js
└── yarn.lock

运行webpack命令

在package.json中添加下面的内容:

"scripts": {
  "build": "webpack"
}

运行yarn build

打开./dist/index.html,哇啦“Hello React 0 to 1”

运行React应用

将./app/index.js里面的内容替换为:

import React from 'react';
import ReactDOM from 'react-dom';

class HelloMessage extends React.Component {
  render() {
    return <div>Hello, {this.props.message}</div>;
  }
}

ReactDOM.render(<HelloMessage message="My First React App" />, document.getElementById('app'));

哇啦“Hello, My First React App”

用DevServer运行

在DevServer中运行,以便实现文件变换监听,自动编译和刷新。

yarn add webpack-dev-server --dev

在webpack的配置文件中添加devServer的配置:

devServer: {
  contentBase: path.join(__dirname, "dist"),
  compress: true,
  host: "0.0.0.0",
  port: 9000,
  hot: true
}

在package.json中添加scripts:

"dev": "webpack-dev-server --hot"

运行yarn dev


本页编辑:Benwei

results matching ""

    No results matching ""