webpack4打包一个项目的基本步骤
首先创建一个目录,例如demo,之后在命令提示行中进入该目录:
进行初始化:
npm init
安装webpack:
npm install webpack --save-dev
安装webpack-cli:
npm install webpack-cli --save-dev
安装webpack-dev-server:
npm install webpack-dev-server --save-dev
在demo目录下新建一个webpack.config.js,初始化它的内容:
var config={
};
module.exports=config;
在package.json的scripts中增加一个快速启动webpack-dev-server服务的脚本:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server --open --config webpack.config.js"
},
在demo目录下新建一个空的main.js作为入口文件,之后在webpack.config.js中进行配置:
var path = require('path');
var config = {
mode:"development",
entry: {
main: "./main"
},
output: {
path:path.join(__dirname,'./dist'),
publicPath:'/dist/',
filename:'main.js'
}
};
module.exports = config;
打包后的文件会存储为demo/dist/main.js,可以在html中引用它。
在demo目录下,新建一个index.html作为SPA的入口:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack</title>
</head>
<body>
<div id="app">
Hello Webpack!
</div>
<script src="/dist/main.js"></script></body>
</html>
在终端执行下面的命令,会在浏览器中自动打开页面:
npm run dev
对css进行处理,安装style-loader和css-loader:
npm install css-loader --save-dev
npm install style-loader --save-dev
对webpack.config.js进行配置:
var path = require('path');
var config = {
mode:"development",
entry: {
main: "./main"
},
output: {
path:path.join(__dirname,'./dist'),
publicPath:'/dist/',
filename:'main.js'
},
module:{
rules:[
{
test:/\.css$/,
use:[
'style-loader',
'css-loader'
]
}
]
}
};
module.exports = config;
在demo目录下新建一个style.css文件:
#app{
color:red;
}
在main.js中导入style.css:
import './style.css'
执行npm run dev命令,可以发现字体变成了红色。
将css提取出来,安装extract-text-webpack-plugin:
npm install extract-text-webpack-plugin@next --save-dev
在webpack.config.js中配置插件:
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var config = {
mode: "development",
entry: {
main: "./main"
},
output: {
path: path.join(__dirname, './dist'),
publicPath: '/dist/',
filename: 'main.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: 'css-loader',
fallback: 'style-loader'
})
}
]
},
//重命名提取后的文件
plugins:[
new ExtractTextPlugin("main.css")
]
};
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack</title>
<link rel="stylesheet" type="text/css" href="/dist/main.css" >
</head>
<body>
<div id="app">
Hello Webpack!
</div>
<script src="/dist/main.js"></script></body>
</html>
可以用以下命令中的一个进行打包:
webpack --mode development
webpack --mode production