在 webpack 4 中,可以无须任何配置使用,然而大多数项目都需要比较复杂的设置。
增加webpack.config.js配置文件,使其目录如下
webpackDemo
|- package.json
+ |- webpack.config.js
|- /dist
|- index.html
|- /src
|- index.js
webpack.config.js代码如下
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
使用新配置文件再次执行构建
#此处的--config webpack.config.js可以省略,默认就是使用webpack.config.js这个文件名
npx webpack --config webpack.config.js
加载CSS
为了从 JavaScript 模块中 import 一个 CSS 文件,你需要在 module 配置中 安装并添加 style-loader 和 css-loader:
npm install style-loader css-loader --save-dev
修改webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
}
};
在项目/src中添加一个新的 style.css 文件
.red {
color: red;
}
src/index.js
//导入lodash
import _ from 'lodash';
//导入样式文件
import './style.css';
function component() {
var element = document.createElement('div');
// Lodash(目前通过一个 script 脚本引入)对于执行这一行是必需的
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
element.classList.add('red');
return element;
}
document.body.appendChild(component());
index.html
<!doctype html>
<html>
<head>
<title>处理css模块</title>
</head>
<body>
<script src="./dist/bundle.js"></script>
</body>
</html>
执行构建
npx webpack
浏览器打开index.html即可看到字体颜色变红了
加载图片
需要用到 file-loader 这个模块
npm install file-loader --save-dev
webpack.config.js增加配置项
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
}
};
/src增加一张图片 icon.png