javascript - webpack 使用babel轉es6的時候出現了問題,但webpack沒有報錯! !急急
怪我咯
怪我咯 2017-05-16 13:45:06
0
2
526

檔案結構:

/ 2017-04-13 webpack_Demo /

    var webpack = require('webpack');
    var path = require('path');
    var glob = require('glob');
    var HtmlWebpackPlugin = require('html-webpack-plugin');
    var Merge = require('webpack-merge');
    var ExtractTextPlugin = require('extract-text-webpack-plugin'); 
    
    var public_PATHS = {
        node_modules_Path: path.resolve('./node_modules'),
        public_resource_Path: path.resolve(process.cwd(), './src/public_resource'),
        vendor_Path: path.resolve(process.cwd(), './src/vendor')
    };
    
    var file_js = getEntry('./src/pages/**/*.js','./src/pages/');
    var file_styles = getEntry('./src/pages/**/*.?(css|less)','./src/pages/');
    var file_html =  getEntry('./src/pages/**/*.html','./src/pages/');
    var pages = Object.keys(file_html);    //get file_html keyval    
    
    //console.log(pages);
    var common_js =getEntry('./src/vendor/js/*.js','./src/vendor/');
        
    var entry_config = Object.assign(file_js,{
        common: [
            'jquery','avalon','lodash','mmRouter'
        ]
    });    //common
    console.log(entry_config);
    
    var output_config = {
        path: __dirname+'/build/pages',
        filename: '[name]-[hash].js'
    };
    
    var module_config ={
        loaders: [
            //css 文件使用 style-loader 和   css-loader 来处理
            {
                   test:/\.css$/,
                   loader:'style-loader!css-loader'
                   
            },
            //在webpack的module部分的loaders里进行配置即可
            { 
                test: /\.js$/,
                exclude: [
                    path.resolve(__dirname, './src/pages'),
                    path.resolve(__dirname, './node_modules')    
                ],
                include:path.resolve(__dirname, './src/pages'),
                loader: 'babel',
                query: {presets: ['es2015']}
            }
        ]
    }
    
    var plugins_config = [
        //warming: this is a Array multips pages web_application need to push htmlwebpackplugin_config_Array
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.$': 'jquery',
          }),
          new webpack.optimize.CommonsChunkPlugin({
            name: 'common',
            filename: "./common/common.js"
        }),
        //new ExtractTextPlugin("avalon_demo.css"),
    ];
    
    pages.forEach(function(pathname) {
        var conf = {
            filename: __dirname+'/build/pages/' + pathname + '.html', //生成的html存放路径,相对于path
            template: path.resolve(__dirname, './src/pages/' + pathname + '.html'), //html模板路径
            //path.resolve(process.cwd(), './src/page'),
            inject: 'head',
            chunks:{
                
            }
            
        };
        plugins_config.push(new HtmlWebpackPlugin(conf));
    });
    var resolve_config = {
        extensions: ['.js', '.css', '.less', '.ejs', '.png', '.jpg','.gif','.html'],    //自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名
        
        alias: {
            jquery: path.join(public_PATHS.vendor_Path, "js/jquery-1.10.2.min.js"),
            avalon: path.join(public_PATHS.vendor_Path, "js/avalon.js"),
            mmRouter: path.join(public_PATHS.vendor_Path, "js/mmRouter.js"),
            lodash: path.join(public_PATHS.vendor_Path, "js/lodash.min.js")
           }    //模块别名定义,方便后续直接引用别名,无须多写长长的地址
       
       //root:public_PATHS
    };
    
    var webpack_config = {
        entry:entry_config,
        output: output_config,
        module:module_config,
        plugins:plugins_config,
        resolve:resolve_config 
    };
    
    
    module.exports = webpack_config;
    
    //common function//
    
    /**
     * 获得路径
     * @param globPath: str
     * @param pathDir: str 对比路径
     * @returns obj 
    */
    function getEntry(globPath, pathDir) {
        //get from github code 
        var files = glob.sync(globPath);
        var entries = {},
            entry,        //文件
            dirname,    //
            basename,    //文件名
            pathname,    //
            extname;    //文件扩展名
    
        for (var i = 0; i < files.length; i++) {
            entry = files[i];
            dirname = path.dirname(entry);    //返回路径中代表文件夹的部分
            //console.log("dirname返回路径中代表文件夹的部分:==>"+dirname);
            extname = path.extname(entry);    //返回路径中文件的后缀名,即路径中最后一个'.'之后的部分。如果一个路径中并不包含'.'或该路径只包含一个'.' 且这个'.'为路径的第一个字符,则此命令返回空字符串。
            //console.log("extname返回路径中文件的后缀名:==>"+extname);
            basename = path.basename(entry, extname);    //返回路径中的最后一部分
            //console.log("basename返回路径中的最后一部分:==>"+basename);
            pathname = path.normalize(path.join(dirname,  basename));    //规范化路径
            //console.log("pathname规范化路径:==>"+pathname);
            pathDir = path.normalize(pathDir);    //规范化路径
            //console.log("pathDir规范化路径:==>"+pathDir);
            if(pathname.startsWith(pathDir)){
                pathname = pathname.substring(pathDir.length);
                //console.log("pathname判断后:==>"+pathname);   
            };
            entries[pathname] = './' + entry;
        }
        //console.log(entries);
        return entries;
    }
    
    
    /* build dev-server */
    
    var npm_run_type = process.env.npm_lifecycle_event;    //get npm run type string
    //console.log("npm_run_type==>"+npm_run_type);
    
    var debug,          // is debug
        devServer,      // is hrm mode
        minimize;       // is minimize
    
    
    
    if (npm_run_type == "build") { // online mode (线上模式)
        debug = false, 
        devServer = false,
        minimize = true;
    }else if (npm_run_type == "build-dev") { // dev mode (开发模式)
        debug = true,
        devServer = false,
        minimize = false;
    } else if (npm_run_type == "dev-hrm") { // dev HRM mode (热更新模式)
        debug = true,
        devServer = true,
        minimize = false;
    };
    /*
     *  Hrm setting
     * (开启热更新,并自动打开浏览器)
     * */
    if (devServer) {
        console.log("port:"+devServer);
        var webpackHot='webpack/hot/dev-server';
        config = Merge(
            config,
            {
                plugins: [
                    // Enable multi-pass compilation for enhanced performance
                    // in larger projects. Good default.
                    new webpack.HotModuleReplacementPlugin({
                        multiStep: true
                    })
                ],
                devServer: {
                    contentBase: __dirname+'/src/',
                    // Enable history API fallback so HTML5 History API based
                    // routing works. This is a good default that will come
                    // in handy in more complicated setups.
                    historyApiFallback: true,
    
                    // Unlike the cli flag, this doesn't set
                    // HotModuleReplacementPlugin!
                    hot: true,
                    inline: true,
    
                    // Display only errors to reduce the amount of output.
                    stats: 'errors-only',
    
                    host: pkg.configs.devHost, 
                    port: pkg.configs.devPort 
                          
                }
            }
        );
    }
    
    //avalon_demo.js
   
    import './avalon_demo.css';
    import username from './moudle.js';
    console.log(username);
    
    //moudle.js
    
     import 'babel-polyfill';
    export default username="stringtest";
    
    
   

json

{
  "name": "webpack_demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-cli": "^6.24.1",
    "babel-core": "^6.24.1",
    "babel-loader": "^6.4.1",
    "babel-polyfill": "^6.23.0",
    "babel-preset-env": "^1.4.0",
    "babel-preset-es2015": "^6.24.1",
    "css-loader": "^0.28.0",
    "ejs-loader": "^0.3.0",
    "extract-text-webpack-plugin": "^2.1.0",
    "file-loader": "^0.11.1",
    "glob": "^7.1.1",
    "html-loader": "^0.4.5",
    "html-webpack-plugin": "^2.28.0",
    "image-webpack-loader": "^3.3.0",
    "jsx-loader": "^0.13.2",
    "postcss-loader": "^1.3.3",
    "style-loader": "^0.16.1",
    "webpack": "^2.4.1",
    "webpack-merge": "^4.1.0"
  }
}

問題說明:專案為多入口多輸出的應用,獨立合併了jquery,avalon等插件為common.js,其他單獨輸出,現在需要babel:es6--轉es5,但是轉完之後沒有報錯但是瀏覽器不能渲染。 moudle的程式碼混在了common中,整個demo chrome 不能解析

現在情況是,我的期望是jQuery四個檔案獨立為common,但是我在avalon_demo.js中import其他檔案moudle.js,按我的想法生成後可能會把moudle和avalon_demo打包,而實際情況是moudle的程式碼在common中,在瀏覽器中找不到export的值。我不知道哪裡出了問題,哪位大哥大姊能幫忙。我在這裡測了好幾個小時了

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回覆(2)
我想大声告诉你

path.resolve(__dirname, './src/pages')這個又exclude又include是乾啥?
沒提供依賴無法具體幫你測試原因,不過可以試試用babel-preset-env替代babel-preset-es2015,最好弄個.babelrc放在外面寫babel的配置項

伊谢尔伦
new webpack.optimize.CommonsChunkPlugin({
        name: 'common',
        filename: "./common/common.js",
        minChunks: Infinity    //仅仅创建公共组件块,不会把任何modules打包进去。并且提供function,以便于自定义逻辑。
    })
    

問題解決 就是添加了minChunks: Infinity 參數 ,和babel配置沒關係,問的題目有一點問題,我把網上轉的api翻譯留在這把,謝謝樓上的兄弟

ptions.name or options.names(string|string[]): 公共模組的名稱
options.filename (string): 公開模組的檔案名稱(產生的檔案名稱)
options.minChunks (number|Infinity|function( module,count) - boolean): 為number表示需要被多少個entries依賴才會被打包到公共代碼庫;為Infinity 僅僅創建公共組件塊,不會把任何modules打包進去。並且提供function,以便於自訂邏輯。
options.chunks(string[]):只對該chunks中的程式碼進行提取。
options.children(boolean):如果為true,那麼公共組件的所有子依賴都將被選擇進來
options.async(boolean|string):如果為true,將創建一個option.name的子chunks(options. chunks的同級chunks) 非同步common chunk
options.minSize(number):所有公用module的size 要大於number,才會建立common chunk

轉自:http://www.cnblogs.com/sloong...

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板