GithubHelp home page GithubHelp logo

blog's People

Contributors

nhyu avatar

blog's Issues

Webpack 怎么做到热刷新和热加载?

1.启用热更新

启用热更新非常的简单只要在webpack配置中增加下面这些配置就可以了。

webpack.config.js的配置

const webpack = require('webpack');
module.exports = {
    devServer: {
        hot: true, // 启用热更新
    },
    plugins: [
        // 当开启 HMR 的时候使用该插件会显示模块的相对路径,建议用于开发环境。
        new webpack.NamedModulesPlugin(),
        // 热替换模块(Hot Module Replacement),也被称为 HMR。
        new webpack.HotModuleReplacementPlugin(),
    ],
}

2.CSS热更新

css热更新只要配置了style-loader就可以了。

webpack.config.js的配置

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            },
        ]
    },
}

3.JS热更新

JS代码实现热更新相对复杂,需要写一些代码来完成。
首先配置还是1.启用热更新中的配置,下面我写一个例子来实现JS热更新。

文件buttonClickHandler.js

export default function () {
    console.log('您点击了按钮!');
}

文件index.js

import buttonClickHandler from './buttonClickHandler';
function createButton(clickHandler) {
    const button = document.createElement('button');
    button.innerText = '我是一个按钮';
    button.addEventListener('click', clickHandler, false);
    return button;
}
let button = createButton(buttonClickHandler);
document.body.appendChild(button);

// 需要额外写的代码
if (module.hot) {
    module.hot.accept('./buttonClickHandler.js', function () {
        console.log('buttonClickHandler 更新了');
        buttonClickHandler();
    });
}

通过上面的例子就实现了js代码的热更新,大家可以修改buttonClickHandler.js中的log测试一下。
也许你会发现,修改完代码后控制台输出的log是改变了,但是点击按钮还是输出了以前的log。为什么呢?因为按钮绑定的监听事件依然是以前的函数,并没有更新成新的函数,我再完善一下。

文件index.js代码修改

function createButton(clickHandler) {
    const button = document.createElement('button');
    button.innerText = '我是一个按钮';
    button.addEventListener('click', clickHandler, false);
    return button;
}
let button = createButton(buttonClickHandler);
document.body.appendChild(button);

// 需要额外写的代码
if (module.hot) {
    module.hot.accept('./buttonClickHandler.js', function () {
        console.log('buttonClickHandler 更新了');
        // buttonClickHandler();
        // 新增加代码
        document.body.removeChild(button);
        button = createButton(buttonClickHandler);
        document.body.appendChild(button);
    });
}

现在再测试就会发现再点击按钮已经实现了输出log的热更新。
其实css也是用的同样的处理方式,只不过loader已经帮我们处理好了。
另外第三方框架也为我们处理好了,不需要我们写这些代码来实现。

搭建 SASS 学习环境

搭建 SASS 学习环境

看了 SASS 的官方文档,但是我并没能清楚的知道我怎么来搭建一个学习环境。于是又搜索了很多大佬的分享才明白,原来这么简单。
参考:Sass 中文网node-sass - npm

准备

  • 请自行安装 node 环境
  • 我的系统是 mac,其他系统的可能会出现命令不一致的情况,请自行解决。

开始安装

直接在控制台运行下面命令,学习环境用到的东西就全了

mkdir my-sass && cd my-sass && npm init -y && npm i -D node-sass

命令解释
mkdir my-sass: 新建一个名字是 my-sass 的文件夹
cd my-sass: 进入 my-sass 文件夹
npm init -y: npm 初始化项目
npm i -D node-sass: 安装 node-sass (最重要的一个命令)

配置环境

在 package.json 的 scripts 中增加一下配置

"scripts": {
    "sass": "node-sass",
    "dev" : "node-sass --watch index.scss output.css"
}

需要改变代码目录的请自行修改命令(例如:"node-sass --watch src/index.scss dist/output.css")
更多命令请参考:https://www.npmjs.com/package/node-sass#command-line-interface
package.json 完整配置在最下面

启动项目

有两种方法进行 sass 编译

先准备测试代码

新建 input.scss 文件

.test {
  color: red;
}

编译方法一

npm run sass input.scss output.css

这个方法每次要编译都要运行一遍编译命令。

编译方法二(自动编译)

npm run dev

使用方法二代码改变会自动进行编译

检查结果

这里你就可以看到项目中多了一个 output.scc 文件,打开应该是这样的

.test {
  color: red;
}

-the end-


package.json 的完整配置

{
  "name": "my-sass",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "sass": "node-sass",
    "dev": "node-sass --watch index.scss output.css"
  },
  "repository": {
    "type": "git",
    "url": ""
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "node-sass": "^5.0.0"
  }
}

Webpack 打包时怎么抽离第三方插件呢?

因为第三方插件变化较少,单独打包可以直接走浏览器缓存,提高加载速度。

1.第三方库单独的入口

module.exports = {
    entry:{
        app: './src/index.js',
        jquery:'jquery', // 要抽离的jquery库
    },
}

2.可以全局引入公共库(可选)

全局引入公共库后代码中不需要再单独引入,可以直接使用$

const webpack = require('webpack');
module.exports = {
    plugins: [
        // 全局引入jquery
        new webpack.ProvidePlugin({
            $:'jquery'
        }),
    ],
}

3.打包抽离公共库配置(Webpack 3)

Webpack 3中已经移除了 webpack.optimize.CommonsChunkPlugin 插件,Webpack 4直接移步下一项

const webpack = require('webpack');
module.exports = {
    plugins: [
        // 抽离公共库
        new webpack.optimize.CommonsChunkPlugin({
            //name对应入口文件中的名字,我们起的是jQuery
            name:['jquery'],
            //把文件打包到哪里,是一个路径
            filename:"[name].js",
            //最小打包的文件模块数
            minChunks:2
        }),
    ],
}

4.打包抽离公共库配置(Webpack 4)

module.exports = {
    optimization: {
        splitChunks: {
            cacheGroups: {
                jquery: {
                    name: "jquery",
                    chunks: "initial",
                    minChunks: 2
                }
            }
        }
    }
}

最终webpack.config.js全部配置

const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry: {
        app: './src/index.js',
        jquery: 'jquery',
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins: [
        // 全局引入jquery
        new webpack.ProvidePlugin({
            $:'jquery'
        }),
        // webpack3.0 单独打包外部库的方法
        // new webpack.optimize.CommonsChunkPlugin({
        //     name:['jquery'], //对应入口文件的jquery(单独抽离)
        //     filename:'[name].js', //抽离到哪里
        //     minChunks: 2, //抽离几个文件
        // }),
    ],
    // webpack4.0 打包外部库的方法
    optimization: {
        splitChunks: {
            cacheGroups: {
                jquery: {
                    name: "jquery",
                    chunks: "initial",
                    minChunks: 2
                }
            }
        }
    }
};

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.