面试被问到webpack配置 - Go语言中文社区

面试被问到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既可以看到我们想要的结果如图
在这里插入图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/maichaoqun/article/details/105539420
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢