./当前目录 ../上级目录
安装、使用
安装
mkdir webpack-demo && cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
//可能会出现以下提示
//We will use "npm" to install the CLI via "npm install -D".
//Do you want to install 'webpack-cli' (yes/no): y
//Installing 'webpack-cli' (running 'npm install -D webpack-cli')...
npm install --save-dev webpack-cli -g
使用一个配置文件
webpack-demo
|- package.json
+ |- webpack.config.js //touch此文件
|- /dist
|- index.html
|- /src
|- index.js
//在webpack.config.js 中写入
const path = require('path');
module.exports = {
//没有src就mkdir
entry: './src/index.js', //源文件是index.js
output: {
filename: 'bundle.js', //处理后的文件dist/bundle.js
path: path.resolve(__dirname, 'dist')
}
};
然后执行npx webpack ,调用项目内部webpack模块
warning解决办法:加上--mode=development一起运行
npx webpack --mode=development
——————————以上webpack可完成基本打包——————————
安装webpack babel
添加将es6转es5功能
https://github.com/babel/babel-loader
7.x版本
npm install --save-dev babel-loader babel-core babel-preset-env webpack
使用
在webpack.config.js中添加
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
然后执行npx webpack
可能出现以下错误:
Error: Cannot find module '@babel/core' //错误
npm install @babel/core //解决
SyntaxError: /workspace/cv/.babelrc: Error while parsing config - JSON5...
vi .babelrc
{
"presets": ["@babel/preset-env"]
}
Error: Cannot find module '@babel/preset-env' from
npm install @babel/preset-env
安装webpack sass
添加翻译sass功能
https://github.com/webpack-contrib/sass-loader
npm install sass-loader node-sass webpack --save-dev
// 在webpack.config.js中添加
module.exports = {
...
module: {
rules: [{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader",
options: {
includePaths: ["absolute/path/a", "absolute/path/b"]
}
}]
}]
}
};
需要在源js文件中import你的scss
然后执行 npx webpack
如果出现错误,缺少什么就install什么
自动加兼容前缀
https://github.com/postcss/postcss-loader
npm i -D postcss-loader
//新建postcss.config.js
module.exports = {
parser: 'sugarss',
plugins: {
'postcss-import': {},
'postcss-preset-env': {},
'cssnano': {}
}
}
//webpack.config.js中添加
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader'
]
}
]
}
}
ERROR:
TypeError: Cannot read property 'bindings' of null
webpack.config.js配置:
module: {
rules:[
{
test: /\.js$/,
loader: 'babel-loader',
exclude: __dirname + 'node_modules',
include: __dirname + 'src',
options: {
presets: ['env']
}
}
]
},