javascript - webpack There was a problem when using babel to convert to es6, but webpack did not report an error! ! Urgently urgently
怪我咯
怪我咯 2017-05-16 13:45:06
0
2
481

File structure:

/ 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"
  }
}

Problem description: The project is a multi-entry and multi-output application. It independently merges jquery, avalon and other plug-ins into common.js, and outputs the others separately. Now we need babel: es6--to convert to es5, but after the conversion, no error is reported but the browser The renderer cannot render. The moudle code is mixed in common, and the entire demo chrome cannot be parsed

The current situation is that my expectation is that the four jQuery files are independent of common, but I import other files moudle.js in avalon_demo.js. According to my idea, moudle and avalon_demo may be packaged after generation, but the actual situation The moudle code is in common, and the export value cannot be found in the browser. I don't know what's wrong and who can help me? I've been testing here for several hours

怪我咯
怪我咯

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

reply all(2)
我想大声告诉你

path.resolve(__dirname, './src/pages') What is the purpose of exclude and include?
I can’t help you test the reason without providing dependencies, but you can try using babel-preset-env instead of babel-preset-es2015. It’s best to make a .babelrc and put it outside to write babel configuration items

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

The problem is solved by adding the minChunks: Infinity parameter. It has nothing to do with babel configuration. There is a problem with the question. I will leave the api translation online here. Thank you to the brother upstairs

ptions.name or options.names(string|string[]): The name of the public module
options.filename (string): The file name of the public module (generated file name)
options.minChunks (number|Infinity|function( module, count) - boolean): Number represents how many entries need to be depended on before it will be packaged into the public code base; for Infinity, only public component blocks are created and no modules will be packaged. And provides functions to facilitate custom logic.
options.chunks(string[]): Only extract the code in the chunks.
options.children(boolean): If true, all sub-dependencies of the public component will be selected.
options.async(boolean|string): If true, a child chunk of option.name will be created (options. Sibling chunks of chunks) Asynchronous common chunk
options.minSize(number): The size of all public modules must be greater than number before a common chunk will be created

Reposted from: http://www.cnblogs.com/sloong...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!