Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

记一次webpack配置过程 #7

Open
Cyrilszq opened this issue Feb 28, 2017 · 0 comments
Open

记一次webpack配置过程 #7

Cyrilszq opened this issue Feb 28, 2017 · 0 comments

Comments

@Cyrilszq
Copy link
Owner

Cyrilszq commented Feb 28, 2017

虽说知道webpack这个东西已经挺久了,但从来没有自己动手配置过,因为一般都是用的脚手架工具(vue-cli)。而且前几天刷2017百度ife的时候,发现习惯了ES6的import后再回到普通的开发方式,引一堆script标签很不适应(而且修改代码后没有热更新)。所以就准备自己搞个模板,这样以后写一些demo的时候就可以直接用模板生成,省的每次都要配webpack。但后来想每次还要从github clone 模板,还是不爽啊,干脆写个简单的脚手架发布到npm上,这样就和vue-cli基础用法差不多了,比如全局安装了脚手架之后直接执行

cyril init

就可以在当前目录生成一个配置好的项目,然后就可以愉快的开发了。关于这个"简陋的"脚手架的更多信息点这里,我配的模板在这里

下面进入主题(基于webpack2)

新建一个配置文件webpack.config.js

// webpack运行时可以提供参数,比如区分是生产环境还是开发环境
module.exports = (options = {}) => {
  return {
    // 在这里写配置
  }
}

配置中比较常见的就是entry(入口文件,webpack会从入口文件开始分析,根据规则选择loader,打包所有依赖),output(输出文件),rules(一些匹配规则),plugins(用到的插件),具体内容如下

entry: {
    main: './src/index.js',
},
output: {
   // 开发环境的话就没必要用chunk了,直接输出默认名字,
    // 生产环境打包时webpack会给文件名加上一段hash,代码改动hash值就会变
    filename: options.dev ? '[name].js' : '[chunkhash].[name].js',
    // 打包到dist目录下
    path: path.resolve(__dirname, 'dist')
},
module: {
    // 配置一些loader
    rules: [
        {
            test: /\.js$/,
            // babel转码时把node_modules中的js排除
            exclude: /node_modules/,
            use: [{
                loader: 'babel-loader',
                // babel配置
                options: {
                    // 暂时只配置转码ES6,并且将modules设为false防止babel将ES6的import转成CommonJS,
                    //因为webpack2是可以自己处理import的
                    presets: [['es2015', {modules: false}]],
                    // 用了几个babel插件,为了使用async/await
                    plugins: [
                        'transform-async-to-generator',
                        'transform-regenerator',
                        'transform-runtime'
                    ]
                }
            }]
        },
        {
            test: /\.html$/,
            use: 'html-loader'
        },
        {
            test: /\.css$/,
            // 将CSS分离打包
            use: ExtractTextPlugin.extract({
                use: 'css-loader'
            })

        },

        {
            test: /\.(png|jpg|jpeg|gif|eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 10000
                    }
                }
            ]
        }
    ]
},
// 在这里注册用到的插件
plugins: [
    // 分离CSS文件
    new ExtractTextPlugin('styles.css'),
    // 处理html的插件,会根据打包结果自动生成script,style标签,
    new HtmlWebpackPlugin({
        template: './index.html'
    }),
    // 以下这段代码直接从vue-cli复制来的,将依赖库和自己开发的文件分开打包,
   // 因为如果打包到一起的话每次本地代码有变动都会重新打包生成新的hash文件名,
    // 这样无法利用浏览器缓存,而其实依赖库的代码一般是没有变动的,分开打包可以利用浏览器缓存
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        minChunks: function (module, count) {
            // any required modules inside node_modules are extracted to vendor
            return (
                module.resource &&
                /\.js$/.test(module.resource) &&
                module.resource.indexOf(
                    path.join(__dirname, './node_modules')
                ) === 0
            )
        }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
        name: 'manifest',
        chunks: ['vendor']
    })
],
// webpack-dev-server的配置
devServer: {
    // 配置本地监听端口
    port: 3000,
    historyApiFallback: true,
    // 在这里可以配置反向代理
    proxy: {
        '/api': {
            target: 'http://localhost:3001',
            secure: false,
            changeOrigin: true,
        }
    }
}

最后还需要改下package.json,使npm run build/dev工作和安装依赖

"devDependencies": {
  "webpack": "^2.2.1",
  "babel-core": "^6.23.1",
  "babel-loader": "^6.3.2",
  "babel-plugin-syntax-dynamic-import": "^6.18.0",
  "babel-plugin-transform-async-to-generator": "^6.22.0",
  "babel-plugin-transform-regenerator": "^6.22.0",
  "babel-plugin-transform-runtime": "^6.23.0",
  "babel-preset-es2015": "^6.22.0",
  "css-loader": "^0.26.2",
  "extract-text-webpack-plugin": "^2.0.0",
  "html-loader": "^0.4.5",
  "html-webpack-plugin": "^2.28.0",
  "rimraf": "^2.6.1",
  "webpack-dev-server": "^2.4.1"
},
"scripts": {
  "build": "rimraf dist && webpack -p",
  "dev": "webpack-dev-server -d --hot --env.dev" 
},

小结

这只是个我为了平时写demo配的webpack,结果就花了我一下午看文档,查资料……虽说也没遇到什么大坑。简单看了一下vuejs-templates的配置,还是挺复杂了。感觉没有做过比较大型的项目,自己对前端工程化这块的理解还是比较浅的。keep learning……

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant