webpack学习
安装node
安装webpack
# 创建一个目录并进入目录
mkdir webpack-demo
cd webpack-demo
# 初始化npm环境配置
npm init -y
# 安装webpack和webpack-cli
npm install --save-dev webpack webpack-cli
或
npm i -D webpack webpack-cli
# 在项目创建src目录并创建index.html index.js index.css 文件
mkdir src
tource index.html
# 在index.js文件中
cat > index.js << EOF
import "./index.css"
console.log("hello world")
EOF
配置webpack.config.js
# 安装html-webpack-plugin
npm install --save-dev html-webpack-plugin
# 安装css-loader style-loader
npm install --save-dev css-loader
# 创建webpack.config.js文件
vim webpack.config.js
# 内容如下
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: __dirname + '/dist',
filename: 'main .js'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html')
})
]
}
# 在package.json文件的script选项中添加"build": "webpack --config webpack.config.js", 格式如下
{
"name": "webpack-demo",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"build": "webpack --config webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"css-loader": "^7.1.2",
"html-webpack-plugin": "^5.6.4",
"style-loader": "^4.0.0",
"webpack": "^5.101.3",
"webpack-cli": "^6.0.1"
}
}
# 执行webpack打包命令
npm run build
webpack多个入口文件
# 方法一
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
mode: 'development',
entry: ['./src/index.js', './src/test.js'],
output: {
path: __dirname + '/dist',
filename: 'main .js'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html')
})
]
}
# 方法二
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
mode: 'development',
entry: {
//index: {
// import: './src/index.js',
//},
test: {
import: './src/test.js',
filename: 'app.js'
}
},
output: {
path: __dirname + '/dist',
filename: 'main .js',
//publicPath: 'http://cdn.com/assets/',
chunkFilename: 'asset_[id].js',
library: {
name: 'my_library',
}
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html')
})
]
}