面试被问到webpack配置

当时太悲剧了,这一块太久没注意,一直都是做项目写业务页面比较多,竟然忘记了,还乱答一通,还说要配置vue-loader、引入path、引入需要应用的函数,时候真想ps自己。

webpack配置:在pakage.json里配置执行命令,然后入口和出口是基本的。
答出以上三点基本得分

安装webpack

首先,安装webpack,这里就直接全局安装

//终端执行,npm不行就用cnpm
npm i webpack -g
//使用webpack4+版本,就要继续安装cli
npm i webpack-cli -g

package.json

接着,开始创建项目文件夹名称改为:webpack
打开终端进入webpack目录下

//-y可以直接默认创建package.json无须一步步配置参数
npm init -y

在这里插入图片描述

创建入口文件

第三步,我喜欢把入口文件放在src目录里,这里需要创建src/main.js
注意这里需要把pakage.json里的main的值改为:"src/main.js"方便阅读

webpack配置

第四步,在webpack目录下创建webpack.config.js

// webpack.config.js
const path = require('path');
const config = {
    entry: './src/main.js', // 配置入口文件
    // 配置:出口文件
    output: {
        path: path.resolve(__dirname, 'dist'), //配置输出路径
        filename: 'bundle.js',//配置:输出文件名称
    },
    mode: 'production', //选择的模式告诉webpack使用其内置的优化:production、development、none
    plugins: []
};

module.exports = config;

配置执行命令

  • 在package.json文件的script里配置执行命令
  • 为了测试在src/main.js写入console.log("Hello Webpack");
    在这里插入图片描述
  • 在终端敲入:npm run start就可以看到dist有一个bundle.js
    在dist里手动创建index.html,然后在里面引入bundle.js,最后打开index.html,你会看到控制台有输出日志:Hello Webpack
    在这里插入图片描述

加入插件

为了简化手动去创建index.html文件,我们加入一个插件

// 如果npm不能下载,可以换cnpm
npm i html-webpack-plugin -D

然后再回到webpack.config.js进行导入和调用

// webpack.config.js
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');//导入插件
const config = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',

    },
    mode: 'production',
    plugins: [
        new htmlWebpackPlugin() //引入插件
    ]
};

module.exports = config;

这个时候删除dist里的所有文件,执行启动命令npm run start就可以看到dist里有index.html
注意这个时候index.html仅插入js文件,但是在body里显示一个div节点怎么办呢?

//如果想在index.html插入一下代码怎么办
<div id="root"></div>

只需要配置html-webpack-plugin插件里的template属性就可以了

// webpack.config.js
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');//导入插件
const config = {
    entry: './src/main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',

    },
    mode: 'production',
    plugins: [
        new htmlWebpackPlugin({
			template: './src/index.html' //创建src/index.html,否则启动会报错
		}) //引入插件
    ]
};

module.exports = config;

如果做好以上配置,没有添加./src/index.html就会报错
在这里插入图片描述
创建src/index.html文件
在这里插入图片描述
最后敲入npm run start既可以看到我们想要的结果如图
在这里插入图片描述

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值