当时太悲剧了,这一块太久没注意,一直都是做项目写业务页面比较多,竟然忘记了,还乱答一通,还说要配置vue-loader、引入path、引入需要应用的函数,时候真想ps自己。
webpack配置:在pakage.json里配置执行命令,然后入口和出口是基本的。
答出以上三点基本得分
首先,安装webpack,这里就直接全局安装
//终端执行,npm不行就用cnpm
npm i webpack -g
//使用webpack4+版本,就要继续安装cli
npm i webpack-cli -g
接着,开始创建项目文件夹名称改为:webpack
打开终端进入webpack目录下
//-y可以直接默认创建package.json无须一步步配置参数
npm init -y
第三步,我喜欢把入口文件放在src目录里,这里需要创建src/main.js
注意这里需要把pakage.json里的main的值改为:"src/main.js"方便阅读
第四步,在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;
console.log("Hello Webpack");
npm run start
就可以看到dist有一个bundle.js为了简化手动去创建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
既可以看到我们想要的结果如图