标签:写代码 echo 快捷方式 append index create 插件 script component
安装
npm install --save-dev webpack
npm install --save-dev webpack-cli //4.x以上版本,用于cli命令
npm install -g webpack
npm install -g webpack-cli
初始化项目
npm init -y //自动生成一个package.json文件
npm install webpack webpack-cli --save-dev
//package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"lodash": "^4.17.5"
}
}
//webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
//index.html
<!doctype html>
<html>
<head>
<title>demo</title>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
//index.js
function component() {
var element = document.createElement('div');
var node = document.createTextNode("hello,webpack!");
element.appendChild(node);
return element;
}
document.body.appendChild(component());
下载安装包
//production模式
npm install --save [+安装包名称]
//development模式
npm install --save-dev
运行项目
npx webpack
//package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "build": "webpack" //新增
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9",
"lodash": "^4.17.5"
}
}
loader
// webpack.config.js
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
]
}
module: {
rules: [
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
}
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
}
module: {
rules: [
{
test: /\.(csv|tsv)$/,
use: [
'csv-loader'
]
},
{
test: /\.xml$/,
use: [
'xml-loader'
]
}
]
}
插件的使用
npm install --save-dev html-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
+ plugins: [
+ new HtmlWebpackPlugin({
+ title: 'Output Management'
+ })
+ ],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
source map
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
+ devtool: 'source-map',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
开发工具
安装
npm install --save-dev webpack-dev-server
使用
//webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
+ devServer: {
+ contentBase: './dist'
+ },
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
标签:写代码 echo 快捷方式 append index create 插件 script component
原文地址:https://www.cnblogs.com/Lazy-Cat/p/10073453.html