webpack基础构建

389 阅读4分钟

计划

1.webpack+ts+react作为项目开发工具
2.git连接jenkins实现自动化发包流程(主要想体验一下这个过程)
3.node编写后台数据可以选用express/koa(目前只会这两个)
4.使用nginx搭建服务

今天是第一天项目基础构建

1.新建一个空文件夹

cd resume
npm init -y //生成基础package.json

2.下载需要的包 webpack webpack-cli

yarn add webpack webpack-cli --dev 

3.简单建一个src文件夹在里面创建一个index.js

mkdir src
cd src
touch index.js
//index.js随便写点东西 例如 console.log('iron man')

4.可以直接执行webpack进行编译(这是webpack4的好处0配置开箱即用直接编译👍)但是我更喜欢按照自己的配置重新建webpack.config.js

注意:执行webpack如果文件目录下有 webpack.config.js会默认执行里面的配置

const path = require('path')

module.exports = {
    mode: "production",
    entry: path.resolve(__dirname, 'src/index.js'),
    output: {
        filename: "[name].[hash:6].js",
        path: path.resolve(__dirname, 'build'),
    }
}

5.接下来配置ts环境

//如果tsc 没找到需要先提前安装一下,或者要是懒得装可以直接百度复制一份tsconfig.json
tsc --init  //生成tsconfig.json
//这是我的配置具体的还有很多推荐去官网看一下
{
  "compilerOptions": {
    // "baseUrl": "./",                       /* 跟随webpack设置的resolve的alias */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],  
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "es2015",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "lib": [ 
      "dom",
      "es5",
      "es2015"],                             /* Specify library files to be included in the compilation. */
    "allowJs": true,                          /* 编译的时候允许有js文件 */
    "checkJs": true,                          /* 验证 js 文件,与 allowJs 一同使用*/
    "jsx": "react",                    
    "declaration": true,     
    "sourceMap": true,             
    "removeComments": true,                /* 去除注释 */
    "noEmit": true,                        /*不显示输出 */
    "downlevelIteration": true,               /* 当 target 为 ES5 或 ES3 时,提供对 for..of,解构等的支持 */
    "strict": true,                         
    "noImplicitAny": true,                 /*不允许隐式类型any*/
    "alwaysStrict": true,                     /* 开启严格模式 */
    "noUnusedParameters": true,            /* 	未使用的参数将报错 */
    "noFallthroughCasesInSwitch": true,    /* switch 语句中,每个 case 都要有 break */
    "allowSyntheticDefaultImports": true,     /* 允许引入没有默认导出的模块 */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  },
  "include": ["src/**/*"],
  "exclude": [
    "node_modules",
  ]
}

6.下面把src下的index.js改成index.ts并且在里面写点ts语法,下载需要的包 babel-loader @babel/core @babel/preset-env @babel/preset-typescript

  • 下载包
 yarn add babel-loader @babel/core @babel/preset-typescript @babel/preset-env -s
  • webpack中要改
entry: path.resolve(__dirname, 'src/index.ts')
  • index.ts中写入
interface fn {
    name:string
}
function Fn(a:fn){
    console.log(a)
}
Fn({name:'iron man'})

7.新建.babelrc文件这里可以给@babel/preset-env配置参数来兼容一些polyfill这里需要下载对应的包 corejs@3

yarn add core-js@3 -s
{
    "presets": [
        [
            "@babel/preset-env",
            {
                "useBuiltIns": "usage", //useBuiltIns 和corejs配合使用
                "corejs": 3
            }
        ],
        "@babel/preset-typescript"
    ]
}

8.下一步配置react需要下载一些包 react react-dom @types/react @types/react-dom @babel/preset-react

  • 下载包
 yarn add react react-dom @types/react @types/react-dom @babel/preset-react -s
  • 我们把index.ts后缀改成js并且在webpack中也要记得改成js后缀(上文改成ts是为了校验ts环境是否配置成功)
 entry: path.resolve(__dirname, 'src/index.js'),
  • index.js中写入
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(<App />, document.getElementById('root'))
  • 根目录下新建public在里面新建index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="root"></div>
</body>
</html>
  • 在src下新建一个App.tsx里面写入一些jsx语法
import React from 'react'
const App = () =>{
    return <div>
    	iron man
        <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597255313238&di=bbb56588ba10d8df2e9d74a65683eb75&imgtype=0&src=http%3A%2F%2Fphoto.16pic.com%2F00%2F34%2F27%2F16pic_3427939_b.jpg" alt=""/>
    </div>
}
export default App
  • 最后修改.babelrc文件新增@babel/preset-react
{
    "presets": [
        [
            "@babel/preset-env",
            {
                "useBuiltIns": "usage", //useBuiltIns 和corejs配合使用
                "corejs": 3
            }
        ],
        "@babel/preset-react",
        "@babel/preset-typescript"
    ]
}

9.为了方便打包和启动服务我们在package.json中配置命令。需要下载包 rimraf,这个包主要用途就是在下次打包之前删除上一次的build

执行 npm run build

注意:如果此时报错了仔细看看上面所说的配置是否都配置了

//yarn add rimraf --dev
 "scripts": {
    "build": "rimraf ./build && webpack"
  }

10.打包成功之后我们配置启动服务命令

//新增start命令
 "scripts": {
    "build": "rimraf ./build && webpack",
    "start": "node ./webpack.config.dev"
  }
  • 根目录下新建webpack.config.dev.js 需要下载包 webpack-dev-server html-webpack-plugin
  • 下载包
yarn add webpack-dev-server html-webpack-plugin --dev
  • webpack.config.dev.js写入
const path = require('path')
const baseConfig = require('./webpack.config')
const webpack = require("webpack");
const compiler = webpack(baseConfig);
const WebpackDevServer = require("webpack-dev-server");

const server = new WebpackDevServer(compiler, {
    hot: true,
    open: true,
    stats: "errors-only",
    historyApiFallback: true,
    compress: true,
});

server.listen(3000, 'localhost', () => {
    console.info(`部署成功,可直接访问http://localhost:3000`);
});
  • webpack.config.js新增html-webpack-plugin配置(顺便把resolve后缀配置加上😁)
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    mode: "production",
    entry: path.resolve(__dirname, 'src/index.js'),
    output: {
        filename: "[name].[hash:6].js",
        path: path.resolve(__dirname, 'build'),
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx|tsx|ts)/,
                loader: 'babel-loader'
            }
        ]
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, "public/index.html")
        }),
    ]
}

最后一步 执行npm start

结束