webpack 学习

113 阅读1分钟

一、入口(entry)

单入口引用:

const config ={
    entry: './path/to/my/entry/file.js'
}

moudle.exports = config


二、出口(output)

单出口引用:

const config = { 
 output: {
    filename: 'bundle.js',
    path: '/home/proj/public/assets'
  }
 }; 
 module.exports = config;


三、loader

loader 用于对模块的源代码进行转换。loader 可以使你在 import 或"加载"模块时预处理文件。因此,loader 类似于其他构建工具中“任务(task)”,并提供了处理前端构建步骤的强大方法

你可以使用 loader 告诉 webpack 加载 CSS 文件,或者将 TypeScript 转为 JavaScript。为此,首先安装相对应的 loader:

npm install --save-dev css-loader 
npm install --save-dev ts-loader

module.exports = {
  module: {
    rules: [
      { test: /\.css$/, use: 'css-loader' },
      { test: /\.ts$/, use: 'ts-loader' }
    ]
  }
};

 

四、插件(plugins)

插件是 webpack 的支柱功能。webpack 自身也是构建于,你在 webpack 配置中用到的相同的插件系统之上!

插件目的在于解决 loader 无法实现的其他事

官网提供了写法:

const HtmlWebpackPlugin = require('html-webpack-plugin'); //通过 npm 安装
const webpack = require('webpack'); //访问内置的插件
const path = require('path');

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    filename: 'my-first-webpack.bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'})
    // 不指定路径默认“dist/index.html”
  ]
};

module.exports = config;

HtmlWebpackPlugin 插件的作用就是生成一个html文件


基本概念就是掌握这四种核心模块的用法。