>  기사  >  웹 프론트엔드  >  webpack으로 구현된 다중 항목 프로젝트 스캐폴딩

webpack으로 구현된 다중 항목 프로젝트 스캐폴딩

巴扎黑
巴扎黑원래의
2017-06-27 09:06:141620검색

소개

webpack2 기반의 다중 항목 프로젝트 스캐폴딩으로, 주로 extract-text-webpack-plugin을 사용하여 js 및 css 공개 코드 추출을 구현하고, html-webpack-plugin을 사용하여 html 다중 항목을 구현하고, less-loader를 사용하여 더 적은 양을 구현합니다. 컴파일 및 postcss-loader 브라우저 호환 접두사를 자동으로 추가하도록 autoprefixer를 구성하고, 이미지 버전 번호와 템플릿을 HTML에 추가하려면 html-withimg-loader를, ES6 트랜스코딩을 구현하려면 babel-loader를, 빌드 속도를 높이기 위해 happypack 멀티스레딩을 구성하세요.

Directory

├── dist                     # 构建后的目录
├── config                   # 项目配置文件
│   ├── webpack.config.js    # webpack 配置文件
│   └── postcss.config.js    # postcss 配置文件
├── src                      # 程序源文件
│   └── js                   # 入口
│   ├   └── index.js         # 匹配 view/index.html
│   ├   └── user         
│   ├   ├    ├── index.js    # 匹配 view/user/index.html
│   ├   ├    ├── list.js     # 匹配 view/user/list.html
│   ├   └── lib              # JS 库等,不参与路由匹配
│   ├       ├── jquery.js 
│   └── view                 
│   ├    └── index.html       # 对应 js/index.js
│   ├    └── user         
│   ├        ├── index.html   # 对应 js/user/index.js
│   ├        ├── list.html    # 对应 js/user/list.js
│   └── css                   # css 文件目录
│   ├    └── base.css          
│   ├    └── iconfont.css     
│   └── font                  # iconfont 文件目录
│   ├    └── iconfont.ttf         
│   ├    └── iconfont.css
│   └── img                   # 图片文件目录
│   ├    └── pic1.jpg         
│   ├    └── pic2.png     
│   └── template              # html 模板目录
│       └── head.html         
│       └── foot.html

Configuration

다중 항목

JS 디렉토리에 따라 다중 항목 배열 가져오기JS 目录获取多入口数组

const ROOT = process.cwd();  // 根目录

let entryJs = getEntry('./src/js/**/*.js');

/**
 * 根据目录获取入口
 * @param  {[type]} globPath [description]
 * @return {[type]}          [description]
 */
function getEntry (globPath) {
    let entries = {};
    Glob.sync(globPath).forEach(function (entry) {
        let basename = path.basename(entry, path.extname(entry)),
            pathname = path.dirname(entry);
        // js/lib/*.js 不作为入口
        if (!entry.match(/\/js\/lib\//)) {
            entries[pathname.split('/').splice(3).join('/') + '/' + basename] = pathname + '/' + basename;
        }
    });
    return entries;
}

// webpack 配置
const config = {
    entry: entryJs,
    output: {
        filename: 'js/[name].js?[chunkhash:8]',
        chunkFilename: 'js/[name].js?[chunkhash:8]',
        path: path.resolve(ROOT, 'dist'),
        publicPath: '/'
    },  
}

module

使用 babel 实现 ES2015 转 ES5,less 转 css 并使用 postcss 实现 autoprefixer 自动添加浏览器兼容,url-loader 实现 css 引用图片、字体添加版本号,html-withimg-loader 实现 html 引用图片添加版本号并实现模板功能。

module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
                loader: 'babel-loader?id=js',
                options: {
                    presets: ['env']
                }
            }
        },
        {
            test: /\.(less|css)$/,
            use: ExtractTextPlugin.extract({
                fallback: 'style-loader?id=styles',
                use: [{
                        loader: 'css-loader?id=styles',
                        options: {
                            minimize:  !IsDev
                        }
                    }, 
                    {
                        loader: 'less-loader?id=styles'
                    }, 
                    {
                        loader: 'postcss-loader?id=styles',
                        options: {
                            config: {
                                path: PostcssConfigPath
                            }
                        }
                    }
                ]
            })
        },
        {
            test: /\.(png|jpg|gif)$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 100,
                        publicPath: '',
                        name: '/img/[name].[ext]?[hash:8]'
                    }
                }
            ]
        },
        {
            test: /\.(eot|svg|ttf|woff)$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 100,
                        publicPath: '',
                        name: '/font/[name].[ext]?[hash:8]'
                    }
                }
            ]
        },
        // @see 
        {
            test: /\.(htm|html)$/i,
            loader: 'html-withimg-loader?min=false'
        }
    ]
},


// postcss.config.js
module.exports = {
    plugins: [
        require('autoprefixer')({
            browsers: ['> 1%', 'last 5 versions', 'not ie <= 9'],
        })
    ]
}

View 视图

根据目录对应关系,获取 js 对应的 html 入口

let entryHtml = getEntryHtml('./src/view/**/*.html'),
    configPlugins;

entryHtml.forEach(function (v) {
    configPlugins.push(new HtmlWebpackPlugin(v));
});

// webpack 配置
resolve: {
    alias: {
        views:  path.resolve(ROOT, './src/view')    
    }
},

/**
 * 根据目录获取 Html 入口
 * @param  {[type]} globPath [description]
 * @return {[type]}          [description]
 */
function getEntryHtml (globPath) {
    let entries = [];
    Glob.sync(globPath).forEach(function (entry) {
        let basename = path.basename(entry, path.extname(entry)),
            pathname = path.dirname(entry),
            // @see 
            minifyConfig = IsDev ? '' : {
                removeComments: true,
                collapseWhitespace: true,
                minifyCSS: true,
                minifyJS: true  
            };

        entries.push({
            filename: entry.split('/').splice(2).join('/'),
            template: entry,
            chunks: ['common', pathname.split('/').splice(3).join('/') + '/' + basename],
            minify: minifyConfig
        });

    });
    return entries;
}

plugins

使用 happypack 多线程加快构建速度,CommonsChunkPlugin 实现提取公用 js 为单独文件,extract-text-webpack-plugin 实现提取公用 css 为单独文件,

let configPlugins = [
    new HappyPack({
        id: 'js',
        // @see 
        threadPool: HappyThreadPool,
        loaders: ['babel-loader']
    }),
    new HappyPack({
        id: 'styles',
        threadPool: HappyThreadPool,
        loaders: ['style-loader', 'css-loader', 'less-loader', 'postcss-loader']
    }),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'common'
    }),
    // @see 
    new ExtractTextPlugin({
        filename: 'css/[name].css?[contenthash:8]',
        allChunks: true
    })
];

entryHtml.forEach(function (v) {
    configPlugins.push(new HtmlWebpackPlugin(v));
});

// webpack 配置
plugins: configPlugins,

开发

webpack-dev-server 实现开发环境自动刷新等功能

// webpack 配置
devServer: {
    contentBase: [
        path.join(ROOT, 'src/')
    ],
    hot: false,
    host: '0.0.0.0',
    port: 8080
}

开发

npm start

http://localhost:8080/view

构建

cross-env 实现区分开发和生产环境构建

rrreeeBabel을 사용하여 ES2015를 ES5로 구현하고 CSS 및 postcss를 사용하여 autoprefixer를 구현하면 브라우저 호환성이 자동으로 추가되고, url-loader는 CSS 참조 이미지를 구현하고 글꼴에 버전 번호를 추가하며, html-withimg-loader는 html 참조 이미지를 구현하고 버전 번호를 추가하며 템플릿 기능을 구현합니다.
命令 说明
npm run dev 开发环境构建,不压缩代码
npm run buildmodule

rrreee

View

디렉토리 대응에 따라 js에 해당하는 html 항목을 가져옵니다.

rrreee
plugins

happypack 멀티스레딩을 사용하여 빌드 속도를 높이고 CommonsChunkPlugin은 공개 js를 별도의 파일로 추출하여 추출합니다. -text-webpack -plugin은 공개 CSS를 별도의 파일로 추출하는 기능을 구현하고,

rrreee🎜Development🎜🎜🎜webpack-dev-server는 개발 환경 자동 새로 고침🎜🎜rrreee🎜Development🎜rrreee🎜🎜http과 같은 기능을 구현합니다. //localhost:8080/view🎜🎜 🎜Build🎜🎜🎜cross-env는 개발 환경과 프로덕션 환경의 구별을 구현합니다. build🎜🎜🎜 thead>🎜npm run dev🎜🎜개발 환경 빌드, 코드 압축 없음🎜🎜🎜npm run build 🎜🎜생산환경 구축, 압축코드🎜🎜🎜🎜🎜warehouse🎜🎜🎜Welcome star🎜🎜🎜🎜🎜🎜🎜재인쇄시 출처를 밝혀주세요:🎜🎜
명령 지침

위 내용은 webpack으로 구현된 다중 항목 프로젝트 스캐폴딩의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.