简体   繁体   English

WebPack和Require

[英]WebPack and Require

I have a module A as follows,Module A is bundles using web pack and it includes Module B. This module also exports Highcharts library using require variable 我有一个如下的模块A,模块A是使用Web Pack的捆绑软件,它包含模块B。该模块还使用require变量导出Highcharts库。

A.js (under modules folder:: src/main/webapp/resources/js/modules) A.js(在modules文件夹下:: src / main / webapp / resources / js / modules)

var HighCharts = require("highchart");
var moduleB = require("../common/B.js"); //so that we can call draw() of moduleB

$(document).ready(function() {
    moduleB.print();
}

B.js (Under Common Folder: src/main/webapp/resources/js/common) B.js(在公共文件夹下:src / main / webapp / resources / js / common)

var print = function() {
console.log("something");
draw();
}
var chart;
function draw() {
    chart = new Highcharts.Chart({

    });
}

exports.print = print;

Note ModuleB.js is bundled in A.js 注意ModuleB.js捆绑在A.js中

When i load the javascript, it is throwing me an error, Highcharts is undefined. 当我加载JavaScript时,它抛出了一个错误,Highcharts未定义。

//how to load this //如何加载

chart = new Highcharts.Chart({

        });

To avoid this error, I did the following. 为避免此错误,我执行了以下操作。

In B.js did the following. 在B.js中执行以下操作。

var Highcharts = require('highcharts'); var Highcharts = require('highcharts');

Also moved B.js into modules folder from common folder, as it is an Entry Point Now(moved to src/main/webapp/resources/js/modules from src/main/webapp/resources/js/common) 还将B.js从通用文件夹移到modules文件夹,因为它是一个Entry Point Now(已从src / main / webapp / resources / js / common移至src / main / webapp / resources / js / modules)

WebPack is giving me the following error. WebPack给我以下错误。
ERROR in ./src/main/webapp/resources/js/modules/A.js Module not found: Error: a dependency to an entry point is not allowed @ ./src/main/webapp/resources/js/modules/A.js 7:14-37 在./src/main/webapp/resources/js/modules/A.js中找不到错误:错误:@。/ src / main / webapp / resources / js / modules / A不允许依赖入口点.js 7:14-37

Webpack.config.js Webpack.config.js

Entry point will be all the files under the modules folder. 入口点将是modules文件夹下的所有文件。

var path = require('path');
var webpack = require("webpack");
var glob = require("glob");
//var BowerWebpackPlugin = require("bower-webpack-plugin");
var jsSrcPath = 'src/main/webapp/resources/js/modules/**/*.js';
var jsDestPath = 'src/main/webapp/resources/build/js/modules';
var cssPath = '';


var files = glob.sync(jsSrcPath, {});
var entries = {};


for (var i = 0; i < files.length; i++) {
  var file = files[i];
  entries[file.replace(/^.*[\\\/]/, '').replace(/\.[^/.]+$/, "")] = path.join(__dirname, file);
}

var webpackOptions = {
  cache: true,
  watch: false,
  entry: entries,
  output: {
    path: __dirname + "/" + jsDestPath,
    filename: '[name].js',
  },
  module: {
    loaders: [{
        test: /.(?:jsx|js)$/,
        exclude: /node_modules/,
        loader: 'babel-loader?blacklist=useStrict'
      },
      // }, {
      //   test: /\.json/,
      //   exclude: /node_modules/,
      //   loader: 'json-loader'
      // }, {
      //   test: /\.css$/,
      //   exclude: /node_modules/,
      //   loader: "style!css"
      // }, {
      //   test: /\.scss$/,
      //   exclude: /node_modules/,
      //   loader: 'style-loader!css-loader!sass-loader!autoprefixer-loader?browsers=last 10 version'
      // }, {
      //   test: /\.(png|jpg)$/,
      //   exclude: /node_modules/,
      //   loader: 'url-loader?limit=999999'
      // }, {
      {
        test: /vendor\/.+\.(jsx|js)$/,
        exclude: /node_modules/,
        loader: 'imports?jQuery=jquery,$=jquery,this=>window'
      }
    ]
  },
  resolve: {
    root: [path.join(__dirname, "bower_components")],
    extensions: ['', '.js', '.json', '.jsx', '.css']
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    // new webpack.optimize.UglifyJsPlugin({
    //   compress: {
    //     warnings: false
    //   }
    // })
  ],
  devServer: {
    contentBase: ".",
    noInfo: true, //  --no-info option
    hot: true,
    inline: true
  }
};



module.exports = webpackOptions;

PS: Initially B.js is outside modules folder as it is not an entry point. PS:最初,B.js不在模块文件夹中,因为它不是入口点。 Later it was moved inside modules folder, as we have made that as an entry point. 后来它被移到modules文件夹中,因为我们将其作为入口点。

"Clearly i don't want to load my highchairs lib in moduleB as it is not an entry point for web pack" “显然,我不想将我的高脚椅子库加载到moduleB中,因为它不是Web Pack的入口点”

This is actually not the case, as unintuitive as it may seem! 实际上并非如此,看起来似乎并不直观! You do need to import Highcharts in moduleB , as that's where you're using it. 您确实需要在moduleB导入Highcharts,因为这是您使用它的地方。 In Node and Webpack, module imports aren't global; 在Node和Webpack中,模块导入不是全局的。 if you had a moduleC with another chart in it, you'd have to import Highcharts there too. 如果您有一个带有其他图表的moduleC ,则也必须在其中导入Highcharts。

Webpack is smart enough to not run/include the imported code twice, so there's no reason to avoid doing this. Webpack非常聪明,不会运行/包含两次导入的代码,因此没有理由避免这样做。 This answer I wrote a while back explains exactly how this works. 我不久前写的答案完全解释了它是如何工作的。

EDIT: Looking at your config, I think you may have the wrong idea about how Webpack works. 编辑:查看您的配置,我认为您可能对Webpack的工作方式有错误的想法。 You don't input a whole directory of files and then get an entire directory full of files back; 您无需输入文件的整个目录,然后再获得包含文件的整个目录。 you set a single file as the entry point, and then Webpack traces all of its dependencies, bundling everything into a single output file*. 您将一个文件设置为入口点,然后Webpack跟踪其所有依赖项,并将所有内容捆绑到一个输出文件中*。 The entry point is, as the name suggests, the point where you enter into your application - you definitely shouldn't be setting every file in your source folder as an entry point like you are now! 顾名思义,入口点是进入应用程序的入口-绝对不应该像现在一样将源文件夹中的每个文件都设置为入口点!

Here is a (hopefully) fixed version of your config: 这是(希望)配置的固定版本:

var path = require('path');
var webpack = require("webpack");
var jsDestPath = 'src/main/webapp/resources/build/js/modules';
var cssPath = '';

var webpackOptions = {
  cache: true,
  watch: false,
  entry: path.join(__dirname, "src/main/webapp/resources/js/modules/a.js"),
  output: {
    path: __dirname + "/" + jsDestPath,
    filename: '[name].js',
  },
  module: {
    loaders: [{
        test: /.(?:jsx|js)$/,
        exclude: /node_modules/,
        loader: 'babel-loader?blacklist=useStrict'
      },
      // }, {
      //   test: /\.json/,
      //   exclude: /node_modules/,
      //   loader: 'json-loader'
      // }, {
      //   test: /\.css$/,
      //   exclude: /node_modules/,
      //   loader: "style!css"
      // }, {
      //   test: /\.scss$/,
      //   exclude: /node_modules/,
      //   loader: 'style-loader!css-loader!sass-loader!autoprefixer-loader?browsers=last 10 version'
      // }, {
      //   test: /\.(png|jpg)$/,
      //   exclude: /node_modules/,
      //   loader: 'url-loader?limit=999999'
      // }, {
      {
        test: /vendor\/.+\.(jsx|js)$/,
        exclude: /node_modules/,
        loader: 'imports?jQuery=jquery,$=jquery,this=>window'
      }
    ]
  },
  resolve: {
    root: [path.join(__dirname, "bower_components")],
    extensions: ['', '.js', '.json', '.jsx', '.css']
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    // new webpack.optimize.UglifyJsPlugin({
    //   compress: {
    //     warnings: false
    //   }
    // })
  ],
  devServer: {
    contentBase: ".",
    noInfo: true, //  --no-info option
    hot: true,
    inline: true
  }
};



module.exports = webpackOptions;

* This is a generalization - you can have multiple entry points, but they need to be independent - they definitely can't import each other.` *这是一个概括-您可以有多个入口点,但是它们必须是独立的-它们绝对不能彼此导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM