webpack初级入门教程(二)

mac2025-10-19  9

1.在根目录创建一个pages文件夹,再在pages文件夹里面创建模块,如下图所示

2.再到webpack.config.js中配置js打包模块的入口和打包后的资源存放路径

entry:{ // 配置多个入口 index:"./pages/index/index.js", login:"./pages/login/index.js", person:"./pages/person/index.js", }, output: { path: path.join(__dirname, 'dist'),//打包文件存放路径__dirname + "/public", // publicPath: '/dist/', //公共路径 filename: "[name].bundle.js"//打包后的文件名字 },

3.用html-webpack-plugin插件配置html打包路径等

安装html-webpack-plugin插件:cnpm install html-webpack-plugin -D

webpack.config.js中写入html-webpack-plugin配置,如下

// 引入path 模块 var path = require('path'); // 引入html-webpack-plugin插件 var HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { devtool: 'eval-soure-map', entry: { // 配置多个入口 index: "./pages/index/index.js", login: "./pages/login/index.js", person: "./pages/person/index.js", }, output: { path: path.join(__dirname, 'dist'), //打包文件存放路径__dirname + "/public", // publicPath: '/dist/', //公共路径 filename: "[name].bundle.js" //打包后的文件名字 }, devServer: { // contentBase: path.join(__dirname, "pages"), contentBase: "./pages", openPage: '/index', //默认打开的页面 host: "192.168.95.237", //设置ip port: 8082, //设置端口号 historyApiFallback: true, inline: true }, module: { rules: [{ test: /(\.jsx|\.js)$/, use: { loader: "babel-loader", options: { } }, exclude: /node_modules/ }, { test: /\.css$/, use: [{ loader: "style-loader", }, { loader: "css-loader", }, ] } ] }, plugins: [ new HtmlWebpackPlugin({ filename: "index/index.html", //打包后在dist文件夹的名字 template: "./pages/index/index.html", //打包的目标文件(模板html) chunks: ['index'], //设置该html仅添加引入的js(模块) minify: { // 压缩HTML文件 removeComments: true, // 移除HTML中的注释 collapseWhitespace: true, // 删除空白符与换行符 minifyCSS: true // 压缩内联css }, }), new HtmlWebpackPlugin({ filename: "login/index.html", template: "./pages/login/index.html", chunks: ['login'], minify: { // 压缩HTML文件 removeComments: true, // 移除HTML中的注释 collapseWhitespace: true, // 删除空白符与换行符 minifyCSS: true // 压缩内联css }, }), new HtmlWebpackPlugin({ filename: "person/index.html", template: "./pages/person/index.html", chunks: ['person'], minify: { // 压缩HTML文件 removeComments: true, // 移除HTML中的注释 collapseWhitespace: true, // 删除空白符与换行符 minifyCSS: true // 压缩内联css }, }), ] }

3.在webpack.config.js中设置端口和ip

devServer: { // contentBase: path.join(__dirname, "pages"), contentBase: "./pages", openPage: '/index', //默认打开的页面 host: "192.168.95.237", //设置ip port: 8082, //设置端口号 historyApiFallback: true, inline: true },

4.加载图片

安装:

npm install --save-dev file-loader

 添加配置

{ test: /\.(png|svg|jpg|gif)$/, use: [{ loader:'file-loader', options:{ name:'[hash:8].[name].[ext]', publicPath:"../images", outputPath:"images/" } }] }

5.html添加图片

最新回复(0)