実行時にwebpackで動的にロードできるモジュラーコンポーネントのシステムを作成しようとしています。たとえば、ユーザーがタブを切り替えた場合、新しいタブのコンテンツを表示するコードは、ユーザーがそのタブをクリックしたときにのみロードする必要があります。
これを実現するコードの一部を次に示します (非常にうまく、追加するかもしれません)。
onrender(){
this.observe("route", (route) => {
if(route.length>0){
this.set("loading", true);
this.get("pages."+route).loadComponent((component) => {
this.components.Page = component.Component;
this.set("loading", false);
});
}
});
},
data: {
pages: {
"#hello": {
name: "Hello",
loadComponent: (callback) => {
require.ensure([], () => {
callback(require("./page_component/hello/hello.js"));
});
}
},
"#world": {
name: "World",
loadComponent: (callback) => {
require.ensure([], () => {
callback(require("./page_component/world/world.js"));
});
}
},
"#activity": {
name: "Individual Activity",
loadComponent: (callback) => {
require.ensure([], () => {
callback(require("./page_component/individual_activity/assets/js/src/main.js"));
});
}
}
}
}
私はこれをうまく機能させましたが、1 つの注意点があります。私はES6を使用しており、babel-loaderを使用してロードしています。タブの機能、テンプレート、スタイルなどを含むモジュールはすべて、次のようにアプリのディレクトリ構造内に直接含まれている必要があります (page_components ディレクトリを参照)。
├── assets
│ ├── css
│ ├── js
│ │ ├── main.js
│ │ └── page_components
│ │ ├── hello
│ │ ├── individual_activity
│ │ └── world
│ └── templates
│ └── index.html
├── package.json
└── webpack.config.js
require("individial_activity")
コードを整理するために、各ページ コンポーネントを package.json を使用して独自のパッケージにし、 example: を介して含めることをお勧めします。
問題は、webpack がnode_modules
ローダーを介して外部モジュール (を介して含まれるモジュールなど) を実行しないように見えるため、ES6 コードをロードしようとすると予期しないシンボルに関するエラーが発生することです。
私はそのようなことを試みましたがrequire("babel-loader!individual_activity")
、require("babel-loader!individual_activity/path/to/main.js")
役に立ちませんでした。
私がやろうとしていることは、通常のやり方ではありませんか? すべてのモジュールのすべてのコードを同じディレクトリ構造に保持する必要がありますか? 私は明らかに間違ったことをしていますか?
webpack.config.js:
var webpack = require("webpack");
module.exports = {
entry: ['./assets/js/main.js'],
output: {
path: './build',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
exclude: /node_modules/,
loader: "style-loader!css-loader"
}
]
},
resolve: {
modulesDirectories: ['node_modules', 'bower_components'],
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
dead_code: true,
conditionals: true,
unsafe: false,
warnings: false
},
mangle: false
}),
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en.js/)
]
};
ありがとう!