Powered by md-Blog  文 - 篇  访客 -

【yarn】简单构建一个 Webpack 项目


更新:2020-03-24 16:26:24  /  创建:2020-03-18 11:22:25  /  分类:Webpack  / 
不要删除
本教程只适用于练习及理解,不推荐在生产开发环境中。

如需生产开发环境,请点击了解:SoEasy-Webpack4.0-Templete,如果对您有所帮助,别忘了给个 Star,谢谢!

1、项目初始化

yarn init -y

2、安装 Webpack

  • webpack 核心模块
  • webpack-cli 命令行工具
yarn add webpack webpack-cli -D

3、验证版本号

npx webpack -v
npx webpack-cli -v

4、新建文件

/src/index.js
import addTxt from './addTxt.js';

document.write('Hello ');
addTxt();
/src/addTxt.js
export default function(){
    document.write('My App');
}
/index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My App</title>
</head>
<body>
    <script src="./dist/bundle.js"></script>
</body>
</html>
/webpack.config.js
const webpack = require('webpack');

module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
    },
    mode: 'development',
    devServer:{
        open: 'opera',
        port: 3000,
        hot: true,
        inline: true,
        quiet: false
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
    ]
}

5、自动清理

yarn add clean-webpack-plugin -D
webpack.config.js
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    plugins: [
        new CleanWebpackPlugin()
    ],
}

6、webpack-dev-server

yarn add webpack-dev-server -D

7、运行脚本

修改 package.json,添加如下脚本
"scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server"
},

运行:

yarn run dev
yarn run build
不要删除

小站不易,感谢支持!