1)构建前端工程化
前言,当我们写vue/React项目的时候,往往会使用官方推荐的脚手架工具自动生成项目,例vue-cli/react-cli脚手架,那今天我们就自己手动构建一个前端工程。
1-1 准备工作
新建项目文件夹
-
npm init -y
//初始化package.json文件 -
npm init webpack webpack-cli webpack-dev-server --save-dev
//webpack4.0版本需要装webpack-cli -
npm init html-webpack-plugin --save-dev
//压缩html的插件
在根目录创建index.html、src文件夹
在src 文件中创建main.js 、js文件夹 、css文件夹、 assets文件夹
![](https://img.haomeiwen.com/i6825620/d1cdd71f576883f7.png)
1-2配置webpack
在根目录创建webpack.config.js文件
并写入
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry : path.resolve(__dirname,'src/main.js'),
output :{
filename : 'js/[name]-[hash].js',
path : path.resolve(__dirname,'dist')
},
devServer : {
disableHostCheck : true
},
plugins : [
new htmlWebpackPlugin({
filename : 'index.html',
template : 'index.html',
minify : {
removeComments : true, //去注释
collapseWhitespace : true //去空格
}
})
]
}
在package.json
"scripts": {
"build" : "webpack",
"dev" : "webpack-dev-server --open"
},
执行 npm run dev
1-3配置解析ES6
安装模块 babel官网
npm install --save-dev babel-loader @babel/core
npm install @babel/preset-env --save-dev
根目录创建[.babelrc]文件
//.babelrc
{
"presets": ["env"]
}
//webpack.config.sj
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry : path.resolve(__dirname,'src/main.js'),
output :{
filename : 'js/[name]-[hash].js',
path : path.resolve(__dirname,'dist')
},
devServer : {
disableHostCheck : true
},
module : {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
]
},
plugins : [
new htmlWebpackPlugin({
filename : 'index.html',
template : 'index.html',
minify : {
removeComments : true, //去注释
collapseWhitespace : true //去空格
}
})
]
}
去试试es6语法有没有解析成功吧~~
网友评论