Webpack Code Separation

I'm trying to set up my project using webpack, I read about code separation, and I'm trying to make two separate packages, one for real application code, and the other for libraries and frameworks. So my webpack configuration looks like this:

entry: {
    app: './app/index.js',
    vendor: './app/vendor.js'
},
output: {
    filename: '[name].[chunkhash].js',
    path: path.resolve(__dirname, 'public/js')
},

watch: true,

module: {
    rules: [{
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            use: 'css-loader'
        })
    }]
},

plugins: [
    new ExtractTextPlugin('styles.css'),
    new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor'
    })
]

in my vendor.js bundle, I have only one line:

 import moment from 'moment';

And when I try to use it in my app.js file, it tells me that this moment is not defined. So, what am I not getting, do the bundles have a total volume or not? If not, how can I access the variables that I exported to another package, and if I can’t, then what is the point of having a bundle of providers, as described here https://webpack.js.org/guides/code-splitting -libraries / ?

+4
3

. webpack , Node.js, - , , .

moment , . , . Webpack , .

, CommonsChunkPlugin , . , , . , , , .


:

import moment from 'moment';
console.log(moment().format());

CommonsChunkPlugin ( ):

vendor.js  470 kB       0  [emitted]  [big]  vendor
   app.js  470 kB       1  [emitted]  [big]  app

470 , moment , , , moment, . , , . - , 470 .

CommonsChunkPlugin:

   app.js  504 bytes       0  [emitted]         app
vendor.js     473 kB       1  [emitted]  [big]  vendor

504 . , ( vendor.js ). , , moment, vendor.js , .

vendor.js , webpack . , vendor.js app.js.

, . . Caching.

+4

, . , :

vendor.js index.js:

vendor.js

export default moment from 'moment';

index.js

var moment = require('vendor.js');
console.log(moment());

:

, . , , $, . - ( "" ), webpack.

require("imports-loader?$=moment,angular!./index.js");

:

momentJS windows , index.js window.moment.

new webpack.ProvidePlugin({
    "window.moment": "moment"
}),
+3

, .js app.js webpack. , , , ...

, var xys{};, ourjsfile.js

And you defined various methods like ..

xyz.add = function(){ ... };

At the end of the file, all you have to do is add ..

module.exports = xyz;

That's all!!! Now, to use this object (variable) in app.js, you must require it, as shown below ...

var xyz = require('./ourjsfile');

And here and there !!! The object is imported. This thing made me pull my hair too long for such a simple solution.

0
source

Source: https://habr.com/ru/post/1673818/


All Articles