目 录CONTENT

文章目录

Webpack多页面配置

Administrator
2020-07-24 / 0 评论 / 0 点赞 / 11260 阅读 / 7777 字

Webpack多页面配置

在webpack下面,单页面的配置是基础,通常会与vue或react等其它一些第三方框架结合使用,但是也可以进行多页面配置,现在将多页面的配置代表列举如下

文件目录结构

1572254613208

package.json配置

{
  "name": "webpack_demo_01",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "cross-env NODE_ENV=production webpack --config webpack.config.js",
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.6.4",
    "@babel/polyfill": "^7.6.0",
    "@babel/preset-env": "^7.6.3",
    "babel-loader": "^8.0.6",
    "clean-webpack-plugin": "^3.0.0",
    "cross-env": "^6.0.3",
    "css-loader": "^3.2.0",
    "cssnano": "^4.1.10",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "file-loader": "^4.2.0",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.0",
    "postcss-cssnext": "^3.1.0",
    "postcss-import": "^12.0.1",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.0",
    "url-loader": "^2.2.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.9",
    "webpack-dev-server": "^3.9.0"
  },
  "browserslist": [
    "defaults",
    "not ie < 11",
    "last 2 versions",
    "> 1%",
    "iOS 7",
    "last 3 iOS versions"
  ]
}

webpack.config.js代码

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
//通过下面的插件来抽离CSS文件
const ExtractTextWebpackPlugin = require("extract-text-webpack-plugin");
// 自动之前之前生成的内容 以全webpack生成新的东西放进去
const {
    CleanWebpackPlugin
} = require("clean-webpack-plugin");

const config = {
    // 多页面配置的入口
    // 在多页的配置里面,每个页面入口会产生两个变量  hash   chunkHash
    entry: {
        index: ["@babel/polyfill", path.join(__dirname, "./src/index.js")],
        login: ["@babel/polyfill", path.join(__dirname, "./src/login.js")]
    },
    output: {
        //多页面配置里面,每个文件的文件名都不一样,根据hash值来生成
        path: path.join(__dirname, "./dist")
    },
    //配置转换规则
    resolve: {
        //配置扩展名省略
        extensions: [".scss", ".css", ".js", ".json"]
    },
    module: {
        rules: [{
            test: /\.js$/,
            use: ["babel-loader"],
            exclude: /node_modules/
        }, {
            //解析图片
            test: /\.(jpg|jpeg|png|svg|bmp|webp|gif)$/,
            //如果要对某一个loader进行单独的配置,我们就给它一个对象进行配置,
            //如果不配置直接往数组里面丢
            use: [{
                loader: "url-loader",
                options: {
                    //8kb
                    limit: 1024 * 8
                }
            }]
        }, {
            //解析字体
            test: /\.(ttf|eot|woff|woff2)$/,
            use: ["url-loader"]
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: "webpack第二课",
            template: "index.html",
            filename: "index.html",
            inject: true,
            chunks: ["index"] //chunks分段的意思,这个网页要插入的分段内容是index入口
        }),
        new HtmlWebpackPlugin({
            title: "登陆页",
            template: "login.html",
            filename: "login.html",
            inject: true,
            chunks: ["login"] //这个网页要插入分段内容是login入口
        }),

    ]
}

//在这里,我要拿一个变量,判断你到底启动的是webpack  还是 webpack-dev-server
const isDev = process.env.NODE_ENV == "development" ? true : false;
if(isDev){
    config.devServer={
        host:"0.0.0.0",
        port:9999,
        contentBase:"./dist",
        hot:false
    }

    //开发环境
    config.output.filename="bundle.[name].[hash].js"; 
    config.module.rules.push({
        test: /\.css$/,
        use: [
            "style-loader",
            "css-loader",
            "postcss-loader"
        ]

    }, {
        test: /\.scss$/,
        use: [
            "style-loader",
            "css-loader",
            "postcss-loader",
            "sass-loader"
        ]
    });
    config.plugins.push(new webpack.HotModuleReplacementPlugin())
}
else{
    //生产环境 
    config.output.filename="bundle.[name].[contentHash].js"; 
    config.module.rules.push({
        //在这里,开发环境与生产环境要不一样,JS与CSS要分离
        test: /\.css$/,
        use: ExtractTextWebpackPlugin.extract({
            // 如果分离失败了,那么,就用style-loader插入到网页里面去
            fallback: "style-loader",
            use: [
                "css-loader",
                "postcss-loader"
            ]
        })
    }, {
        test: /\.scss$/,
        use: ExtractTextWebpackPlugin.extract({
            fallback: "style-loader",
            use: [
                "css-loader",
                "postcss-loader",
                "sass-loader"
            ]
        })
    });
    config.plugins.push(
        new CleanWebpackPlugin(),
        new ExtractTextWebpackPlugin({
        filename: "[name]-[hash].css"
    }))
}
//根据环境变量,重新设置webpack的模式
config.mode=process.env.NODE_ENV;


module.exports = config;

.babelrc文件配置

{
    "presets": ["@babel/preset-env"]
}

postcss.config.js文件配置

module.exports={
    plugins:[
        require("postcss-import"),
        require("postcss-cssnext"),
        require("cssnano")
    ]
}

该项目有两个入口,分别是index.jslogin.js

login.js代码

/**
 * 登陆页面的JS
 */

import Student from "./Student";

newFunction();

async function newFunction() {
    let s = new Student("杨标登陆", 18);
    let result = await s.sayHello();
    console.log(result);
}

//导入CSS文件
import "../css/login";

index.js代码


// 因为我们已经配置了webpack里面的resolve中的extensions, 所以可以省略后缀名
import Student from "./Student";


newFunction();

console.log("hello world");

async function newFunction() {
    let s = new Student("杨标");
    let result = await s.sayHello();
    console.log(result);
}

// 导入 CSS文件
import "../css/index";

//导入 SCSS文件
import "../scss/index";

::: tip 说明
未完待续

因时间关系 ,后面的公共文件提取,目录创建等未写在笔记里面
:::

0

评论区