使用webpack搭建前端项目
Step1 先生成一个package.json, 安装webpack脚手架
1、新建一个项目,先安装。运行下面两条指令
npm init -y
npm i -D webpack webpack-cli typescript ts-loader
2、接着配置webpack环境,新建webpack.config.js
配置文件,内容如下:
entry是入口文件的相对地址;module里会给各种文件配置规则,比如我们先配一个ts文件的规则,使用的是ts-loader
的依赖;output是打包之后生成文件的位置,在dist
文件下。
//webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader'
}
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
}
}
3、添加tsconfig.json
文件并新增配置
{
"compilerOptions": {
"jsx": "react",
"target": "ES2015",
"module": "ES2015",
"strict": true
}
}
4、配置package.json
在scripts
选项中添加
"scripts": {
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1",
},
5、以上配置完成,在index.tsx
中输入代码:
const str: string = 'hello, world';
console.log(`name: ${
str}`);
6、控制台输入npm run build
,可以看到项目目录中生成了dist
目录,里边有一个打包后的文件bundle.js
。
Step2 引入HTML
1、引入HTMLWebpackPlugin
插件
npm i -D html-webpack-plugin
html-wepback-plugin
插件会自动在打包时生成一个html文档,并自动引入打包之后的bundle.js
文件
2、配置webpack
plugins: [
new HTMLWebpackPlugin()
]
编译,dist
目录下生成了index.html
文件。
3、自定义html文件
在src
文件下面新建public
文件夹,新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="