webpack初始化项目
初始化webpack
在创建项目的目录下启动webpack
npm init -y
npm install webpack --save-dev
npm install webpack-cli --save-dev
不建议全局安装webpack,因为这可能会影响到其他项目webpack的版本.
webpack目录结构
/dist
为打包输出目录
/src
为源代码目录
package-lock-json
:是锁定安装时的包的版本号,并且需要上传到git,以保证其他人在npm install时大家的依赖能保证一致
package.json
:定义了这个项目所需要的各种模块,以及项目的配置信息(比如名称、版本、许可证等元数据)
webpack-config.js
:Webpack 在执行的时候,除了在命令行传入参数,还可以通过指定的配置文件来执行。默认情况下,会搜索当前目录的 webpack.config.js 文件
package.json
"+“表示新增代码,”-"表示删除代码
调整package.json文件,以确保将包标记为私有,并删除main入口。这是为了防止意外发布代码
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
+ "private": true,
- "main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.20.2",
"webpack-cli": "^3.1.2"
},
"dependencies": {}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
//导出环境:development,production
mode:"development",
//当js发生错误的时候,会帮助你导航到错误的地方
//开发环境推荐:cheap-module-eval-source-map
//生产环境推荐:cheap-module-source-map
devtool: 'cheap-module-eval-source-map',
//入口
entry: {
"index":['./src/index.js']
},
//provides you with a simple web server and the ability to use live reloading.
//安装:npm install --save-dev webpack-dev-server
//在package.json中添加 "build": "webpack-dev-server",让启动更快捷. 直接使用npm run build
//可能会用到Hot Module Replacement.热模块更新. 这里没有配置
devServer: {
contentBase: './dist',
open: true,
port: 8080
},
module: {
rules: [
{ //npm install -D babel-loader @babel/core @babel/preset-env webpack.
//Babel 是 JavaScript 编译器。
//中文文档地址:https://babel.docschina.org/
test: /\.js$/,
exclude: /node_modules/,
use: { loader: 'babel-loader',options: { presets: ['@babel/preset-env'] } }
},
{ //npm install url-loader --save-dev
test: /\.(png|jpg|gif)$/,
use: [ { loader: 'url-loader',options: { limit: 8192 } } ]
},
{ //npm install --save-dev style-loader css-loader sass-loader node-sass
test: /\.css$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
},
{ //加载字体文件 npm install --save-dev file-loader
test: /\.(eot|ttf|svg)$/,
use: {loader: 'file-loader'}
}
]
},
//用于删除/清除构建文件夹的webpack插件。 npm install --save-dev clean-webpack-plugin
//简化创建HTML文件,可以让插件生成HTML文件。 npm install --save-dev html-webpack-plugin
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
],
//出口
output: {
filename: 'js/[name].js',
path: path.resolve(__dirname, 'dist')
}
};