零基础搭使用webpack脚手架搭建前端页面

使用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="
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值