1.webpack核心概念
1.入口(entry)
表示告诉webpack从哪个文件作为构建其内部依赖图的开始。
// 单个引入
const config = {
entry: {
main: './path/to/my/entry/file.js'
}
};
// 单个的简写
module.exports = {
entry: './path/to/my/entry/file.js'
};
// 多个引入
module.exports = {
entry: {
pageOne: './src/pageOne/index.js',
pageTwo: './src/pageTwo/index.js',
pageThree: './src/pageThree/index.js'
}
};
2.输出(output)
控制 webpack 如何向硬盘写入编译文件。注意,即使可以存在多个入口起点,但只指定一个输出配置。
module.exports = {
output: {
filename: 'bundle.js', // 输出的文件名
path: '/home/proj/public/assets' // 输出目录的绝对路径
}
};
// 常见写法
var path = require('path'); // path是node的内置模块
module.exports = {
output: {
filename: '[name].js', // [name]是占位符,配置入口entry键值对里的key值。占位符详情可见https://www.webpackjs.com/configuration/output/#output-filename
path: path.resolve(__dirname, './dist') // __dirname是node的全局对象,表示当前运行的目录名。 path.resolve将路径/路径段 解析为绝对路径
}
};
3.loader(module)
loader 用于对模块的源代码进行转换。loader 可以在 import 或"加载"模块时预处理文件。
module.exports = {
module: {
rules: [
{ test: /\.css$/, use: 'css-loader' },
{ test: /\.ts$/, use: 'ts-loader' }
]
}
};
4.插件(plugins)
webpack 插件是一个具有 apply 属性的 JavaScript 对象。
插件可以携带参数/选项,你必须在 webpack 配置中,向 plugins 属性传入 new 实例。
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 webpack.optimize.UglifyJsPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'})
]
};
module.exports = config;