标签 - webpack 共找到结果 2 条

Vue构建的大多是SPA单页面应用,但有时候在实际项目中单页面应用并不一定符合业务需求

准备工作

利用vue-cli新建项目,再执行npm install命令安装所需依赖,之后需安装新依赖glob

npm install --save-dev glob

修改webpack配置

需要改动的文件都在build文件夹下:

  • util.js
  • webpack.base.conf.js
  • webpack.dev.conf.js
  • webpack.prod.conf.js

utils.js 文件

// glob是webpack安装时依赖的一个第三方模块,还模块允许你使用 *等符号
// 例如lib/*.js就是获取lib文件夹下的所有js后缀名的文件
const glob = require('glob');
// 页面模版文件路径
const page_path = path.join(__dirname, '../src/module');
// 页面模板插件
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 融合相应的配置
const merge = require('webpack-merge');

// 多页面入口文件配置
// 通过glob模块读取pages文件夹下的所有对应文件夹下的js后缀文件,如果该文件存在
// 那么就作为入口文件之一
exports.entry = _ => {
  var entryFiles = glob.sync(page_path + '/*/*.js');
  var map = {};
  entryFiles.map(filePath => {
      let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'));
      map[filename] = filePath;
  });
  return map;
}

// 多页面输出配置
// 与上面的多页面入口文件配置相同,读取pages文件夹下的对应的html后缀文件,然后放入数组中
exports.HtmlWebpackPlugin = _ => {
  var entryFiles = glob.sync(page_path + '/*/*.html');
  var arr = [];
  entryFiles.map(filePath => {
      let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'));
      let config = {
          // 模板来源
          template: filePath,
          // 文件名称
          filename: filename + '.html',
          inject: true,
          // 页面模板需要加对应的js脚本,如果不加这行则每个页面都会引入所有的js脚本
          chunks: ['manifest', 'vendor', filename]
      }
      // 生产环境加入新配置,该配置是原webpack.prod.conf.js中相对于webpack.dev.conf.js新增配置
      if (process.env.NODE_ENV === 'production') {
          config = merge(config, {
              minify: {
                  removeComments: true,
                  collapseWhitespace: true,
                  removeAttributeQuotes: true
              },
              chunksSortMode: 'dependency'
          })
      }
      arr.push(new HtmlWebpackPlugin(config));
  });
  return arr;
}

webpack.base.conf.js 文件

原:

entry: {
    app: './src/main.js'
},

替换成

entry: utils.entry(),

webpack.dev.conf.js 文件

注释掉:

plugins: [
    // new HtmlWebpackPlugin({
    //     filename: 'index.html',
    //     template: 'index.html',
    //     inject: true
    // }),
]

并在

plugins: [].concat(utils.HtmlWebpackPlugin())

webpack.prod.conf.js 文件

同上注释掉:

plugins: [
    // new HtmlWebpackPlugin({
    //     filename: config.build.index,
    //     template: 'index.html',
    //     inject: true,
    //     minify: {
    //         removeComments: true,
    //         collapseWhitespace: true,
    //         removeAttributeQuotes: true
    //             // more options:
    //             // https://github.com/kangax/html-minifier#options-quick-reference
    //     },
    //     // necessary to consistently work with multiple chunks via CommonsChunkPlugin
    //     chunksSortMode: 'dependency'
    // }),
]

并在

plugins: [].concat(utils.HtmlWebpackPlugin())

至此,webpack的配置就结束了。

文件结构

.
├── README.md
├── build
│   ├── build.js
│   ├── check-versions.js
│   ├── logo.png
│   ├── utils.js
│   ├── vue-loader.conf.js
│   ├── webpack.base.conf.js
│   ├── webpack.dev.conf.js
│   └── webpack.prod.conf.js
├── config
│   ├── dev.env.js
│   ├── index.js
│   └── prod.env.js
├── package.json
├── src
│   ├── assets
│   │   └── logo.png
│   ├── components
│   │   ├── Hello.vue
│   │   └── cell.vue
│   └── module
│       ├── cell
│       │   ├── cell.html
│       │   ├── cell.js
│       │   └── cell.vue
│       └── index
│           ├── index.html
│           ├── index.js
│           ├── index.vue
│           └── router
│               └── index.js
└── static

src为默认工程文件,其中的assets,components,module分别是静态资源文件、组件文件、页面文件。 页面文件中按照项目的模块分的文件夹,每个文件夹下分别有三个内容:vue文件,js文件和html文件。这三个文件的作用就相当于做spa单页面应用时,根目录的index.html页面模板,src文件下的main.jsapp.vue的功能。

现在可以直接运行npm start试试看效果

相关代码:

参考地址:

阅读全文

公司最近这个项目用的是spring boot,但是又需要前端使用Vue.js进行开发,单独使用requireJS和Vue.js配合又不方便,所以想到了直接使用webpack开发.

以下webpack介绍copy自:《入门Webpack,看这篇就够了》

为什要使用WebPack

现今的很多网页其实可以看做是功能丰富的应用,它们拥有着复杂的JavaScript代码和一大堆依赖包。为了简化开发的复杂度,前端社区涌现出了很多好的实践方法:

  • 模块化,让我们可以把复杂的程序细化为小的文件;
  • 类似于TypeScript这种在JavaScript基础上拓展的开发语言:使我们能够实现目前版本的JavaScript不能直接使用的特性,并且之后还能转换为JavaScript文件使浏览器可以识别;
  • Scss,less等CSS预处理器
  • ...

这些改进确实大大的提高了我们的开发效率,但是利用它们开发的文件往往需要进行额外的处理才能让浏览器识别,而手动处理又是非常繁琐的,这就为WebPack类的工具的出现提供了需求。

以下贴出我的配置文件:

1. webpack.base.config.js: (PS:这只是基础配置,因为还需要一个webpack生产环境,所以把代理单独提到webpack开发环境配置中)
/**
 * webpack配置基础
 */
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');
const vendor = ["iview", "vuex", "vue-router", "echarts"];
const config = {
    entry: {
        main: './app/main.js',
        vendor: vendor //CommonsChunkPlugin打包第三方
    },
    output: {
        filename: '[name].js',
        path: path.join(__dirname + '/public/dist/'),
        publicPath: '/public/dist/'
    },
    resolve: {
        alias: {
            'vue$': 'vue/dist/vue.common.js'
        }
    },
    externals: {
        'jquery': 'window.jQuery',
        'moment': 'window.moment',
    }, //较大的库引用cdn文件
    module: {
        rules: [{
                test: /.vue$/,
                loader: 'vue-loader',
                options: {
                    loader: {
                        css: ExtractTextPlugin.extract({
                            use: ['css-loader'],
                            fallback: 'style-loader'
                        })
                    }
                }
            },
            {
                test: /.js$/,
                exclude: /node_modules/, //编译打包时需要排除 node_modules 文件夹
                loader: "babel-loader",
                query: { presets: ['es2015'] }
            },
            {
                test: /.scss$/,
                // loader: "style-loader!css-loader"
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: ["css-loader", "sass-loader"]
                })
            },
            {
                test: /.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: ['css-loader']
                })
            },
            {
                test: /.(gif|jpg|png|woff|woff2|ttf|svg|eot$)??.*$/,
                loader: "url-loader?limit=10240&name=./[name].[ext]?[hash]"
            }
        ]
    },
    plugins: [
        new OpenBrowserPlugin({ url: 'http://localhost:3000' }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.$': 'jquery'
        }), //这个可以使jquery变成全局变量,不用在自己文件require('jquery')了
        new webpack.optimize.CommonsChunkPlugin({
            name: ['vendor'],
            filename: 'common.js'
        }), //第三方库打包生成的文件
        new ExtractTextPlugin({
            filename: '[name].css',
            allChunks: true
        }), //分离 CSS 和 JS 文件.
    ]
};
module.exports = config;
2. webpack.config.js:
/**
 * webpack开发环境
 */
 
const merge = require("webpack-merge");
const WebpackBaseConfig = require("./webpack.base.config");
 
module.exports = merge(WebpackBaseConfig, {
    devServer: {
        port: 3000,
        proxy: {
            '*': {
                //后台地址
                target: 'http://localhost:8080',
                secure: false,
                prependPath: false,
                changeOrigin: true
            }
        },
        publicPath: '/public/dist/',
        historyApiFallback: true
    }
});
3. webpack.prod.config.js:
/**
 * webpack生产环境
 */
 
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const merge = require("webpack-merge");
const WebpackBaseConfig = require("./webpack.base.config");
WebpackBaseConfig.plugins = [];
WebpackBaseConfig.module.rules[1] = {
    test: /.js$/,
    //通常需要忽略node_modules,但iviews包含es6代码,压缩时需要转换成es5
    // exclude: /node_modules/, //编译打包时需要排除 node_modules 文件夹
    loader: "babel-loader",
    query: { presets: ['es2015'] }
}
module.exports = merge(WebpackBaseConfig, {
    output: {
        filename: '[name].[hash].js',
        publicPath: '/public/dist/'
    },
    plugins: [
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.$': 'jquery'
        }), //这个可以使jquery变成全局变量,不用在自己文件require('jquery')了
        new webpack.optimize.CommonsChunkPlugin({
            name: ['vendor'],
            filename: 'common.[hash].js'
        }), //第三方库打包生成的文件
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        //在这个数组中new一个实例就可以了
        new webpack.BannerPlugin("Copyright mrabit."),
        //为组件分配 ID,通过这个插件 Webpack 可以分析和优先考虑使用最多的模块,并为它们分配最小的 ID.
        new webpack.optimize.OccurrenceOrderPlugin(), 
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                drop_debugger: false,
                drop_console: false
            }
        }), //压缩JS代码.
        new ExtractTextPlugin({
            filename: '[name].[hash].css',
            allChunks: true
        }), //分离 CSS 和 JS 文件.
        new HtmlWebpackPlugin({
            filename: '../../index.html',
            template: './index.ejs',
            inject: false
        })
    ]
});
4. 通过上面的配置可实现webpack-dev-server3000端口去代理8080端口。在package.json中添加:
"scripts": {
    "dev": "rimraf public/dist/* && webpack-dev-server --host 0.0.0.0 --history-api-fallback --inline --hot",
    "build": "rimraf public/dist/* && webpack --progress --config webpack.prod.config.js"
},
5. 之后直接启动spring boot后台,然后npm run dev就可以通过访问3000端口来进行前端的开发了.
6. 当然,这里推荐使用微软的VSCode,虽然我平时用的都是WebStorm,但是相对于webpack开发,VSCode确实要流畅很多

阅读全文