webpack 单入口项目基础配置教程(八)

这次我们处理下 全局问题(比如 jq 的全局变量)

这个在网上的解决方案非常多 我随便用一个应付一下你们

先装上 jq

yarn add jquery

然后修改 webpack.config.js 文件

const path = require('path');
+const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: './src/app.jsx',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'js/app.js'
    },
    module: {
        rules: [
            {
                test: /\.jsx$/,
                exclude: /(node_modules)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env', 'es2015', 'react']
                    }
                }
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                })
            },
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader', 'sass-loader']
                })
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192,
                            name: 'resource/[name].[ext]'
                        }
                    }
                ]
            },
            {
                test: /\.(svg|woff|woff2|eot|ttf|otf)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192,
                            name: 'resource/[name].[ext]'
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'MY-WEBPACK',
            template: './src/index.html'
        }),
        new ExtractTextPlugin("css/[name].css"),
+        new webpack.ProvidePlugin({
+            $: 'jquery',
+            jQuery: 'jquery'
+        })
    ],
    optimization: {
        splitChunks: {
            chunks: "all",
            name: 'common'
        }
    },
};

修改 app.jsx 文件

import React from 'react';
import ReactDOM from 'react-dom';

import 'font-awesome/css/font-awesome.min.css';
import './index.css';
import './index.scss';

+ console.log($('#app'))

ReactDOM.render(
    

Hello, world!

, document.getElementById('app') );

就这样 打包之后打开浏览器在 console 里就可以看到 jq 选择器生效了

但是你可能会看到一坨的报错, 说找不到各种静态资源文件

这个报错其实在我们整理 dist 文件夹之后就有了, 即时解决的方法不是没有, 但是正常项目怎么可能有那个场景, 我觉得没必要去解决

接着我们搞下最后一个需求 架设 webpack 中间服务器(热更新) 顺便处理下找不到静态资源文件的问题

你可能感兴趣的:(webpack 单入口项目基础配置教程(八))