npm i webpack -g
在编辑js的时候使用node,然后使用webpack
打包成bundle.js
在导入到html中.
这样做的好处是
webpack main.js bundle.js
webpack.config.js
来配置webpack
const path = require('path')
module.exports = {
entry: path.join(__dirname, './src/main.js'),
output: {
path.join(__dirname, './dist',
filename: 'bundle.js'
}
}
webpack-dev-server依赖于webpack,必须安装在本项目中
npm i webpack
npm i webpack-dev-server
webpack-dev-server打包的bundle.js并没有放在物理磁盘里,而是放在了内存里,所以根目录找不到bundle.js.在根目录里/bundle.js
npm i webpack
npm i webpack-dev-server
npm i html-webpack-plugin
不用手动导入jswebpack.config.js
来配置webpackconst path = require('path')
var htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.join(__dirname, './src/main.js'),
output: {
path: path.join(__dirname, './dist'),
filename: 'bundle.js'
},
plugins:[ // 添加plugins节点配置插件
new htmlWebpackPlugin({
template:path.resolve(__dirname, 'src/index.html'),//模板路径
filename:'index.html'//自动生成的HTML文件的名称
})
]
}
dev
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --port 3000 --contentBase src --hot"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"jquery": "^3.4.1",
"webpack": "^4.34.0",
"webpack-dev-server": "^3.7.1"
},
"devDependencies": {
"webpack-cli": "^3.3.4"
}
}
参数 | 描述 |
---|---|
open | 自动打开浏览器 |
port | 监听端口 |
contentBase src | 自动打开src文件夹中的index,默认是根目录,不是src |
hot | 异步,不用手动刷新 |
npm run dev
1.安装npm i style-loader css-loader
2.配置第三方文件的匹配规则,新建module节点
module: { // 用来配置第三方loader模块的
rules: [ // 文件的匹配规则
{ test: /\.css$/, use: ['style-loader', 'css-loader'] }//处理css文件的规则
]
}
cnpm i url-loader file-loader
webpack.config.js
中添加处理url路径的loader模块:{ test: /\.(png|jpg|gif)$/, use: 'url-loader' }
limit
指定进行base64编码的图片大小;只有小于指定字节(byte)的图片才会进行base64编码:{ test: /\.(png|jpg|gif)$/, use: 'url-loader?limit=43960' },
安装npm i bootstrap
import `bootstrap/dist/css/bootstrap.css`
{test: /\.(ttf|eot|svg|woff|woff2)$/,use: 'url-loader'}
如果用了es6的新语法则需要用babel进行语法降级打包
cnpm i babel-core babel-loader babel-plugin-transform-runtime
cnpm i babel-preset-env babel-preset-stage-0
webpack.config.js
中添加相关loader模块,排除node_modules,不要编译别人写好的包{ test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }
.babelrc
文件,并修改这个配置文件如下:{
"presets":["env", "stage-0"],
"plugins":["transform-runtime"]
}