webpack和knockoutjs没有" externals"?

时间:2017-09-25 05:04:20

标签: knockout.js webpack

是否可以将knockoutjs与webpack一起使用?现在,我的html中只有以下内容

<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>

和webpack配置中的条目一样

externals: {
    'ko': 'ko'
}

我希望使用yarn安装的任何版本的ko。

似乎与knockoutjs中的这个this line有关,并且似乎有某种暗示可以解决此问题over here

理想情况下,我仍然希望使用脚本标记(由webpack注入到html中),但我认为如果只能以某种方式从node_modules加载knockout,我可以弄明白自己......

如何在没有我的webpack配置中的require条目的情况下使用纱线安装externals敲门声?

4 个答案:

答案 0 :(得分:1)

巨大的成功。在问题中的链接之后,我设法通过webpack config

中的以下条目滚动它
module: {
  loaders: [
    {
      test: /knockout.build.output.knockout-latest\.js/,
      loader: "imports?require=>false"
    }
  ]
}

然后我可以require('knockout')

答案 1 :(得分:0)

还有另一种解决方案。您可以使用IgnorePlugin

const webpack = require("webpack");

module.exports = [
    {
        entry: {
            "knockout": [
             // Inside file below there is 'require("knockout")' 
             // invocation which webpack cannot resolve.
             // We need to tell webpack to not to resolve that
             // and leave 'require("knockout")' whithout any changes.
             // By that this code will be resolved on runtime
             // which means that we need to attach script to 
             // knockout somewhere in project. 
             "./js/knockout/knockout.mapping-latest.js",
            ]
        },
        output: {
            filename: "./dist/[name].js"
        },
        plugins: [
            // This tells to webpack: if you'll find 
            // somewhere in code 'require("knockout")'
            // don't try to resolve that. Leave it as is. 
            new webpack.IgnorePlugin(/^knockout$/),
        ]
    }
];

答案 2 :(得分:0)

我能够淘汰掉webpack。 加入淘汰赛后,我的项目进展顺利。

npm我淘汰赛-保存

在webpack.config.js中,我使用的module.exports插件为

  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      Util: 'exports-loader?Util!bootstrap/js/dist/util',
      ko: 'exports-loader?!knockout'
    })

然后,我能够在输入文件中导入敲除:

import './index.scss';
import 'bootstrap/js/src/tab';
import 'bootstrap/js/src/modal';
import 'knockout';

答案 3 :(得分:-1)

将knockout放入module.exports.entry部分,它正在运行。你需要的只是把它包含在你的js文件中,就像require('knockout')一样。

  

webpack.config.js

module.exports.entry = {
    vendor: [
        'jquery',
        'knockout',
        'bootstrap'            
    ],
    emal_patient_form : [
        path.resolve(__dirname, 'resources/js/EmalPatientForm.js')
    ]
};
...
  

... /resources/js/EmalPatientForm.js

...
const ko = require("knockout");
const myViewModel = {
     error_messsage: ko.observable(''),
     alert: ko.observable('')
 };
ko.applyBindings(myViewModel);
...