webpack应用配置

介绍

webpack 是一个现代 JavaScript 应用程序的静态模块打包工具
为众多开源项目所使用,本地开发神器,十分便捷

安装

1
2
3
4
mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev

目录结构

1
2
3
4
5
  webpack-demo
|- package.json
+ |- index.html
+ |- /src
+ |- index.js

添加webpack配置文件

1
vim webpakc.config.js

基础配置

1
2
3
4
5
6
7
8
9
const path = require('path');

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

package.json

1
2
3
4
5
{
"scripts": {
"build": "webpack --config webpack.config.js"
}
}

常用插件及其设置

HtmlWebpackPlugin

自动替换html文件

安装

1
npm install --save-dev html-webpack-plugin

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  const path = require('path');
+ const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js',
},
+ plugins: [
+ new HtmlWebpackPlugin({
+ title: 'Output Management',
+ template: './index.html'
+ }),
+ ],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};

clean-webpack-plugin

自动生成文件仅是覆盖原文件,多余的文件并未清理

安装

1
npm install --save-dev clean-webpack-plugin

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
+ const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js',
},
plugins: [
+ new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};

开发环境 webpack-dev-server

安装

1
npm install --save-dev webpack-dev-server

配置

webpakc.config.js

1
2
3
4
    devtool: 'inline-source-map',
+ devServer: {
+ contentBase: './dist',
+ },

package.json

1
2
3
4
5
{
"scripts": {
"start": "webpack-dev-server --open"
}
}

常用loader

file-loader
将图片作为一个文件,生成到输出目录, (如果指定了选项,则使用指定的命名约定) 并返回文件的 public URI。

安装

1
npm install file-loader --save-dev

配置webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
],
},
};

官方详细介绍

raw-loader
文件源码载入 github地址
glsl vert,webgl开发很方便哦

安装

1
2
3
4
npm install raw-loader --save-dev

# usage: command-line
webpack --module-bind 'txt=raw-loader'

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
module.exports = {
module: {
rules: [
{
test: /\.(glsl|vs|txt|fs|vert|frag)$/,
exclude: /node_modules/,
use: 'raw-loader',
},
],
},
};

resolve

当目录文件复杂之后,各个目录的文件引用及日后转移将会是件麻烦的事
为此,我们需要使用路径的引用来解决这个问题

修改webpack.config.js

1
2
3
4
5
6
7
8
9
module.exports = {
//...
resolve: {
alias: {
'~': path.resolve(__dirname, 'src/'),
'~assets': path.resolve(__dirname, 'src/assets'),
}
}
};

KEEP UPDATE

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×